update.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package actions
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. log "github.com/go-admin-team/go-admin-core/logger"
  6. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  7. "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
  8. "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
  9. "git.cestong.com.cn/cecf/hx-admin-server/common/dto"
  10. "git.cestong.com.cn/cecf/hx-admin-server/common/models"
  11. )
  12. // UpdateAction 通用更新动作
  13. func UpdateAction(control dto.Control) gin.HandlerFunc {
  14. return func(c *gin.Context) {
  15. db, err := pkg.GetOrm(c)
  16. if err != nil {
  17. log.Error(err)
  18. return
  19. }
  20. msgID := pkg.GenerateMsgIDFromContext(c)
  21. req := control.Generate()
  22. //更新操作
  23. err = req.Bind(c)
  24. if err != nil {
  25. response.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
  26. return
  27. }
  28. var object models.ActiveRecord
  29. object, err = req.GenerateM()
  30. if err != nil {
  31. response.Error(c, 500, err, "模型生成失败")
  32. return
  33. }
  34. object.SetUpdateBy(user.GetUserId(c))
  35. //数据权限检查
  36. p := GetPermissionFromContext(c)
  37. db = db.WithContext(c).Scopes(
  38. Permission(object.TableName(), p),
  39. ).Where(req.GetId()).Updates(object)
  40. if db.Error != nil {
  41. log.Errorf("MsgID[%s] Update error: %s", msgID, err)
  42. response.Error(c, 500, err, "更新失败")
  43. return
  44. }
  45. if db.RowsAffected == 0 {
  46. response.Error(c, http.StatusForbidden, nil, "无权更新该数据")
  47. return
  48. }
  49. response.OK(c, object.GetId(), "更新成功")
  50. c.Next()
  51. }
  52. }