request_list.go 4.5 KB

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