request_list.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. package rest_gorm
  2. import (
  3. "fmt"
  4. "reflect"
  5. "git.ali33.ru/fcg-xvii/go-tools/json"
  6. "git.ali33.ru/fcg-xvii/rest"
  7. "gorm.io/gorm"
  8. "gorm.io/gorm/clause"
  9. )
  10. type List struct {
  11. Conditions rest.ConditionList `json:"Conditions" swagger:"items=$ref:rest.Condition"`
  12. Orders []*rest.Order `json:"Orders" swagger:"items=$ref:rest.Order"`
  13. Offset int `json:"Offset"`
  14. Limit int `json:"Limit"`
  15. }
  16. func (s *List) Prepare() {
  17. if s.Limit <= 0 || s.Limit > 20 {
  18. s.Limit = 20
  19. }
  20. }
  21. func (s *List) Result(pg *gorm.DB, fields rest.FieldNamesList, res any) (count int64, err rest.IErrorArgs) {
  22. s.Prepare()
  23. for i, cond := range s.Conditions {
  24. if !cond.Logic.IsValid() {
  25. err = rest.ErrorFiled(cond.Field, "Unexpected logic")
  26. return
  27. }
  28. if !cond.Operator.IsValid() {
  29. err = rest.ErrorFiled(cond.Field, "Unexpected operator")
  30. return
  31. }
  32. if !fields.Exists(cond.Field) {
  33. err = rest.ErrorFiled(cond.Field, "Unexpected field")
  34. return
  35. }
  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)
  50. } else {
  51. pg = pg.Or(q)
  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. }
  79. func toAnySlice(slice any) []any {
  80. v := reflect.ValueOf(slice)
  81. if v.Kind() == reflect.Ptr {
  82. v = v.Elem()
  83. }
  84. // Check if the input is a slice
  85. if v.Kind() != reflect.Slice {
  86. return nil
  87. }
  88. result := make([]any, v.Len())
  89. for i := 0; i < v.Len(); i++ {
  90. result[i] = v.Index(i).Interface()
  91. }
  92. return result
  93. }
  94. func (s *List) ResultAnswer(pg *gorm.DB, fields rest.FieldNamesList, res any, offset, limit int) (*ResultList, rest.IErrorArgs) {
  95. count, err := s.Result(pg, fields, res)
  96. if err != nil {
  97. return nil, err
  98. }
  99. rList := &ResultList{
  100. Items: toAnySlice(res),
  101. Offset: offset,
  102. Limit: limit,
  103. Count: count,
  104. }
  105. return rList, nil
  106. }
  107. func (s *List) ResultOut(pg *gorm.DB, model any, req rest.IRequestIn) rest.IRequestOut {
  108. fieldNames, err := rest.FieldNames(model)
  109. if err != nil {
  110. return req.OutError(rest.ErrorMessage("ErrFileds", err.Error()))
  111. }
  112. // preload
  113. if pg, err = Preload(model, req.Fields(), pg); err != nil {
  114. return req.OutError(rest.ErrorMessage("ErrPreload", err.Error()))
  115. }
  116. // Определяем тип элемента напрямую без использования reflect.ValueOf
  117. elemType := reflect.TypeOf(model)
  118. // Создаем срез нужного типа
  119. sl := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 0)
  120. // Создаем указатель на этот срез
  121. slPtr := reflect.New(sl.Type())
  122. // Устанавливаем значение созданного среза в указатель
  123. slPtr.Elem().Set(sl)
  124. // Передаем указатель на срез
  125. return s.ResultOutNames(pg, fieldNames, slPtr.Interface(), req)
  126. }
  127. func (s *List) ResultOutNames(pg *gorm.DB, fields rest.FieldNamesList, res any, req rest.IRequestIn) rest.IRequestOut {
  128. rList, err := s.ResultAnswer(pg, fields, res, s.Offset, s.Limit)
  129. if err != nil {
  130. return req.OutError(err)
  131. }
  132. return rList.Out(req)
  133. }
  134. type ResultList struct {
  135. Items []any `json:"Items" rest:"fixed"`
  136. Offset int `json:"Offset" rest:"fixed"`
  137. Limit int `json:"Limit" rest:"fixed"`
  138. Count int64 `json:"Count" rest:"fixed"`
  139. }
  140. func (s *ResultList) Map(req rest.IRequestIn) (json.Map, rest.IErrorArgs) {
  141. fields := req.Fields()
  142. ml := make([]json.Map, 0, len(s.Items))
  143. for _, item := range s.Items {
  144. it, ierr := rest.Fields(item, nil, fields)
  145. if ierr != nil {
  146. return nil, ierr
  147. }
  148. ml = append(ml, it)
  149. }
  150. res := json.Map{
  151. "Items": ml,
  152. "Offset": s.Offset,
  153. "Limit": s.Limit,
  154. "Count": s.Count,
  155. }
  156. return res, nil
  157. }
  158. func (s *ResultList) Out(req rest.IRequestIn) rest.IRequestOut {
  159. m, ierr := s.Map(req)
  160. if ierr != nil {
  161. return req.OutError(ierr)
  162. }
  163. return req.OutSuccess(m, nil)
  164. }