request_list.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package rest_gorm
  2. import (
  3. "fmt"
  4. "log"
  5. "git.ali33.ru/fcg-xvii/rest"
  6. "gorm.io/gorm"
  7. "gorm.io/gorm/clause"
  8. )
  9. type List struct {
  10. Conditions rest.ConditionList `json:"Conditions" swagger:"items=$ref:rest.Condition"`
  11. Orders []*rest.Order `json:"Orders" swagger:"items=$ref:rest.Order"`
  12. Offset int `json:"Offset"`
  13. Limit int `json:"Limit"`
  14. }
  15. func (s *List) Prepare() {
  16. if s.Limit <= 0 || s.Limit > 20 {
  17. s.Limit = 20
  18. }
  19. }
  20. func (s *List) Result(pg *gorm.DB, fields rest.FieldNamesList, res any) (count int64, err rest.IErrorArgs) {
  21. s.Prepare()
  22. for i, cond := range s.Conditions {
  23. if !cond.Logic.IsValid() {
  24. err = rest.ErrorFiled(cond.Field, "Unexpected logic")
  25. return
  26. }
  27. if !cond.Operator.IsValid() {
  28. err = rest.ErrorFiled(cond.Field, "Unexpected operator")
  29. return
  30. }
  31. if !fields.Exists(cond.Field) {
  32. err = rest.ErrorFiled(cond.Field, "Unexpected field")
  33. return
  34. }
  35. log.Println("CV", cond.Value)
  36. if cond.Value == nil {
  37. q := fmt.Sprintf("%s %s ?", CamelToSnake(cond.Field), cond.Operator)
  38. if i == 0 || cond.Logic == rest.LogicAND {
  39. pg = pg.Where(q, cond.Value)
  40. } else {
  41. pg = pg.Or(q, cond.Value)
  42. }
  43. } else {
  44. if cond.Operator != "" && cond.Operator != rest.OperatorNot {
  45. err = rest.ErrorFiled(cond.Field, "Expected empty operator or not")
  46. }
  47. q := fmt.Sprintf("%s is %s null", CamelToSnake(cond.Field), cond.Operator)
  48. if i == 0 || cond.Logic == rest.LogicAND {
  49. pg = pg.Where(q, cond.Value)
  50. } else {
  51. pg = pg.Or(q, cond.Value)
  52. }
  53. }
  54. }
  55. // count
  56. if dbRes := pg.Count(&count); dbRes.Error != nil {
  57. err = rest.ErrorFiled("ErrDB", dbRes.Error.Error())
  58. return
  59. }
  60. // offset limit
  61. pg = pg.Offset(s.Offset).Limit(s.Limit)
  62. // orders
  63. for _, order := range s.Orders {
  64. pg = pg.Order(
  65. clause.OrderByColumn{
  66. Column: clause.Column{
  67. Name: CamelToSnake(order.Name),
  68. },
  69. Desc: !order.IsAsc,
  70. },
  71. )
  72. }
  73. if pg = pg.Find(res); pg.Error != nil {
  74. err = rest.ErrorFiled("ErrDB", pg.Error.Error())
  75. return
  76. }
  77. return
  78. }