list.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package field_management
  2. import (
  3. "adm-management/consts"
  4. "adm-management/errors"
  5. "adm-management/model"
  6. v1 "adm-management/pb/v1"
  7. "context"
  8. "encoding/json"
  9. "fmt"
  10. "git.getensh.com/common/gopkgsv2/database"
  11. "git.getensh.com/common/gopkgsv2/logger"
  12. "go.uber.org/zap"
  13. "google.golang.org/grpc/status"
  14. "gorm.io/gorm"
  15. )
  16. func Field(ctx context.Context, req *v1.FieldRequest) (reply *v1.FieldReply, err error) {
  17. defer func() {
  18. if r := recover(); r != nil {
  19. err = fmt.Errorf("%+v", r)
  20. e := &status.Status{}
  21. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  22. logger.Error("err",
  23. zap.String("system_err", err.Error()),
  24. zap.Stack("stacktrace"))
  25. }
  26. }
  27. }()
  28. reply = &v1.FieldReply{}
  29. db := database.DB()
  30. if req.Field != "" {
  31. db = db.Where("`field` like ?", "%"+req.Field+"%")
  32. }
  33. if req.Desc != "" {
  34. db = db.Where("`desc` like ?", "%"+req.Desc+"%")
  35. }
  36. pageSize := consts.PageSize
  37. if req.PageSize != 0 {
  38. pageSize = int(req.PageSize)
  39. }
  40. // 构造分页类
  41. pagination := model.NewPagination(int(req.Page), pageSize, 0).GetLimitOffset()
  42. count, err := model.NewFieldList().Count(db)
  43. if err != nil && err != gorm.ErrRecordNotFound {
  44. return reply, errors.SystemError
  45. }
  46. if err == gorm.ErrRecordNotFound || count == 0 {
  47. return reply, nil
  48. }
  49. list, err := model.NewFieldList().List(db, pagination)
  50. if err != nil && err != gorm.ErrRecordNotFound {
  51. return reply, errors.SystemError
  52. }
  53. if err == gorm.ErrRecordNotFound {
  54. pagination.CalPage(int(count))
  55. reply.CurrentPage = int64(pagination.CurrentPage)
  56. reply.PerPage = int64(pagination.PerPage)
  57. reply.Total = int64(pagination.Total)
  58. reply.FirstPage = int64(pagination.FirstPage)
  59. reply.LastPage = int64(pagination.LastPage)
  60. reply.PrevPage = int64(pagination.PrevPage)
  61. reply.NextPage = int64(pagination.NextPage)
  62. return reply, nil
  63. }
  64. reply.List = make([]*v1.Field, 0, len(list))
  65. for _, v := range list {
  66. reply.List = append(reply.List, &v1.Field{
  67. Field: v.Field,
  68. Desc: v.Desc,
  69. Type: "string",
  70. })
  71. }
  72. // 计算分页结果
  73. pagination.CalPage(int(count))
  74. reply.CurrentPage = int64(pagination.CurrentPage)
  75. reply.PerPage = int64(pagination.PerPage)
  76. reply.Total = int64(pagination.Total)
  77. reply.FirstPage = int64(pagination.FirstPage)
  78. reply.LastPage = int64(pagination.LastPage)
  79. reply.PrevPage = int64(pagination.PrevPage)
  80. reply.NextPage = int64(pagination.NextPage)
  81. return reply, nil
  82. }