request_list.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package rest_gorm
  2. import (
  3. "fmt"
  4. "log"
  5. "reflect"
  6. "git.ali33.ru/fcg-xvii/go-tools/json"
  7. "git.ali33.ru/fcg-xvii/rest"
  8. "gorm.io/gorm"
  9. "gorm.io/gorm/clause"
  10. )
  11. type List struct {
  12. Conditions rest.ConditionList `json:"Conditions" swagger:"items=$ref:rest.Condition"`
  13. Orders []*rest.Order `json:"Orders" swagger:"items=$ref:rest.Order"`
  14. Offset int `json:"Offset"`
  15. Limit int `json:"Limit"`
  16. }
  17. func (s *List) Prepare() {
  18. if s.Limit <= 0 || s.Limit > 20 {
  19. s.Limit = 20
  20. }
  21. }
  22. func (s *List) Result(pg *gorm.DB, fields rest.FieldNamesList, res any) (count int64, err rest.IErrorArgs) {
  23. s.Prepare()
  24. for i, cond := range s.Conditions {
  25. if !cond.Logic.IsValid() {
  26. err = rest.ErrorFiled(cond.Field, "Unexpected logic")
  27. return
  28. }
  29. if !cond.Operator.IsValid() {
  30. err = rest.ErrorFiled(cond.Field, "Unexpected operator")
  31. return
  32. }
  33. if !fields.Exists(cond.Field) {
  34. err = rest.ErrorFiled(cond.Field, "Unexpected field")
  35. return
  36. }
  37. if cond.Value != nil {
  38. q := fmt.Sprintf("%s %s ?", CamelToSnake(cond.Field), cond.Operator)
  39. if i == 0 || cond.Logic == rest.LogicAND {
  40. pg = pg.Where(q, cond.Value)
  41. } else {
  42. pg = pg.Or(q, cond.Value)
  43. }
  44. } else {
  45. if cond.Operator != "" && cond.Operator != rest.OperatorNot {
  46. err = rest.ErrorFiled(cond.Field, "Expected empty operator or not")
  47. }
  48. q := fmt.Sprintf("%s is %s null", CamelToSnake(cond.Field), cond.Operator)
  49. if i == 0 || cond.Logic == rest.LogicAND {
  50. pg = pg.Where(q)
  51. } else {
  52. pg = pg.Or(q)
  53. }
  54. }
  55. }
  56. // count
  57. if dbRes := pg.Count(&count); dbRes.Error != nil {
  58. err = rest.ErrorFiled("ErrDB", dbRes.Error.Error())
  59. return
  60. }
  61. // offset limit
  62. pg = pg.Offset(s.Offset).Limit(s.Limit)
  63. // orders
  64. for _, order := range s.Orders {
  65. pg = pg.Order(
  66. clause.OrderByColumn{
  67. Column: clause.Column{
  68. Name: CamelToSnake(order.Name),
  69. },
  70. Desc: !order.IsAsc,
  71. },
  72. )
  73. }
  74. if pg = pg.Find(res); pg.Error != nil {
  75. err = rest.ErrorFiled("ErrDB", pg.Error.Error())
  76. return
  77. }
  78. log.Println(res)
  79. return
  80. }
  81. func toAnySlice(slice any) []any {
  82. v := reflect.ValueOf(slice)
  83. log.Println("kk", v.Kind())
  84. if v.Kind() == reflect.Ptr {
  85. v = v.Elem()
  86. }
  87. // Check if the input is a slice
  88. if v.Kind() != reflect.Slice {
  89. return nil
  90. }
  91. result := make([]any, v.Len())
  92. for i := 0; i < v.Len(); i++ {
  93. result[i] = v.Index(i).Interface()
  94. }
  95. return result
  96. }
  97. func (s *List) ResultAnswer(pg *gorm.DB, fields rest.FieldNamesList, res any, offset, limit int) (*ResultList, rest.IErrorArgs) {
  98. count, err := s.Result(pg, fields, res)
  99. if err != nil {
  100. return nil, err
  101. }
  102. log.Println("---", res)
  103. rList := &ResultList{
  104. Items: toAnySlice(res),
  105. Offset: offset,
  106. Limit: limit,
  107. Count: count,
  108. }
  109. return rList, nil
  110. }
  111. func (s *List) ResultOut(pg *gorm.DB, model any, req rest.IRequestIn) rest.IRequestOut {
  112. fieldNames, err := rest.FieldNames(model)
  113. if err != nil {
  114. return req.OutError(rest.ErrorMessage("ErrFileds", err.Error()))
  115. }
  116. // preload
  117. log.Println("list preload...")
  118. if pg, err = Preload(model, req.Fields(), pg); err != nil {
  119. return req.OutError(rest.ErrorMessage("ErrPreload", err.Error()))
  120. }
  121. // Определяем тип элемента напрямую без использования reflect.ValueOf
  122. elemType := reflect.TypeOf(model)
  123. log.Println(elemType)
  124. // Создаем срез нужного типа
  125. sl := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 0)
  126. // Создаем указатель на этот срез
  127. slPtr := reflect.New(sl.Type())
  128. // Устанавливаем значение созданного среза в указатель
  129. slPtr.Elem().Set(sl)
  130. // Передаем указатель на срез
  131. return s.ResultOutNames(pg, fieldNames, slPtr.Interface(), req)
  132. }
  133. func (s *List) ResultOutNames(pg *gorm.DB, fields rest.FieldNamesList, res any, req rest.IRequestIn) rest.IRequestOut {
  134. rList, err := s.ResultAnswer(pg, fields, res, s.Offset, s.Limit)
  135. if err != nil {
  136. return req.OutError(err)
  137. }
  138. return rList.Out(req)
  139. }
  140. type ResultList struct {
  141. Items []any `json:"Items" rest:"fixed"`
  142. Offset int `json:"Offset" rest:"fixed"`
  143. Limit int `json:"Limit" rest:"fixed"`
  144. Count int64 `json:"Count" rest:"fixed"`
  145. }
  146. func (s *ResultList) Map(req rest.IRequestIn) (json.Map, rest.IErrorArgs) {
  147. fields := req.Fields()
  148. ml := make([]json.Map, 0, len(s.Items))
  149. for _, item := range s.Items {
  150. it, ierr := rest.Fields(item, nil, fields)
  151. if ierr != nil {
  152. return nil, ierr
  153. }
  154. ml = append(ml, it)
  155. }
  156. res := json.Map{
  157. "Items": ml,
  158. "Offset": s.Offset,
  159. "Limit": s.Limit,
  160. "Count": s.Count,
  161. }
  162. return res, nil
  163. }
  164. func (s *ResultList) Out(req rest.IRequestIn) rest.IRequestOut {
  165. m, ierr := s.Map(req)
  166. if ierr != nil {
  167. return req.OutError(ierr)
  168. }
  169. return req.OutSuccess(m, nil)
  170. }