request_list.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. q := fmt.Sprintf("%s %s ?", CamelToSnake(cond.Field), cond.Operator)
  35. if i == 0 || cond.Logic == rest.LogicAND {
  36. pg = pg.Where(q, cond.Value)
  37. } else {
  38. pg = pg.Or(q, cond.Value)
  39. }
  40. }
  41. // count
  42. if dbRes := pg.Count(&count); dbRes.Error != nil {
  43. err = rest.ErrorFiled("ErrDB", dbRes.Error.Error())
  44. return
  45. }
  46. // offset limit
  47. pg = pg.Offset(s.Offset).Limit(s.Limit)
  48. // orders
  49. for _, order := range s.Orders {
  50. pg = pg.Order(
  51. clause.OrderByColumn{
  52. Column: clause.Column{
  53. Name: CamelToSnake(order.Name),
  54. },
  55. Desc: !order.IsAsc,
  56. },
  57. )
  58. }
  59. if pg = pg.Find(res); pg.Error != nil {
  60. err = rest.ErrorFiled("ErrDB", pg.Error.Error())
  61. return
  62. }
  63. return
  64. }