request_list.go 2.0 KB

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