request_list.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. if pg, err = Preload(model, req.Fields(), pg); err != nil {
  118. return req.OutError(rest.ErrorMessage("ErrPreload", err.Error()))
  119. }
  120. // Определяем тип элемента напрямую без использования reflect.ValueOf
  121. elemType := reflect.TypeOf(model)
  122. log.Println(elemType)
  123. // Создаем срез нужного типа
  124. sl := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 0)
  125. // Создаем указатель на этот срез
  126. slPtr := reflect.New(sl.Type())
  127. // Устанавливаем значение созданного среза в указатель
  128. slPtr.Elem().Set(sl)
  129. // Передаем указатель на срез
  130. return s.ResultOutNames(pg, fieldNames, slPtr.Interface(), req)
  131. }
  132. func (s *List) ResultOutNames(pg *gorm.DB, fields rest.FieldNamesList, res any, req rest.IRequestIn) rest.IRequestOut {
  133. rList, err := s.ResultAnswer(pg, fields, res, s.Offset, s.Limit)
  134. if err != nil {
  135. return req.OutError(err)
  136. }
  137. return rList.Out(req)
  138. }
  139. type ResultList struct {
  140. Items []any `json:"Items" rest:"fixed"`
  141. Offset int `json:"Offset" rest:"fixed"`
  142. Limit int `json:"Limit" rest:"fixed"`
  143. Count int64 `json:"Count" rest:"fixed"`
  144. }
  145. func (s *ResultList) Map(req rest.IRequestIn) (json.Map, rest.IErrorArgs) {
  146. fields := req.Fields()
  147. ml := make([]json.Map, 0, len(s.Items))
  148. for _, item := range s.Items {
  149. it, ierr := rest.Fields(item, nil, fields)
  150. if ierr != nil {
  151. return nil, ierr
  152. }
  153. ml = append(ml, it)
  154. }
  155. res := json.Map{
  156. "Items": ml,
  157. "Offset": s.Offset,
  158. "Limit": s.Limit,
  159. "Count": s.Count,
  160. }
  161. return res, nil
  162. }
  163. func (s *ResultList) Out(req rest.IRequestIn) rest.IRequestOut {
  164. m, ierr := s.Map(req)
  165. if ierr != nil {
  166. return req.OutError(ierr)
  167. }
  168. return req.OutSuccess(m, nil)
  169. }