123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package rest_gorm
- import (
- "fmt"
- "log"
- "git.ali33.ru/fcg-xvii/rest"
- "gorm.io/gorm"
- "gorm.io/gorm/clause"
- )
- type List struct {
- Conditions rest.ConditionList `json:"Conditions" swagger:"items=$ref:rest.Condition"`
- Orders []*rest.Order `json:"Orders" swagger:"items=$ref:rest.Order"`
- Offset int `json:"Offset"`
- Limit int `json:"Limit"`
- }
- func (s *List) Prepare() {
- if s.Limit <= 0 || s.Limit > 20 {
- s.Limit = 20
- }
- }
- func (s *List) Result(pg *gorm.DB, fields rest.FieldNamesList, res any) (count int64, err rest.IErrorArgs) {
- s.Prepare()
- for i, cond := range s.Conditions {
- if !cond.Logic.IsValid() {
- err = rest.ErrorFiled(cond.Field, "Unexpected logic")
- return
- }
- if !cond.Operator.IsValid() {
- err = rest.ErrorFiled(cond.Field, "Unexpected operator")
- return
- }
- if !fields.Exists(cond.Field) {
- err = rest.ErrorFiled(cond.Field, "Unexpected field")
- return
- }
- log.Println("CV", cond.Value)
- if cond.Value == nil {
- q := fmt.Sprintf("%s %s ?", CamelToSnake(cond.Field), cond.Operator)
- if i == 0 || cond.Logic == rest.LogicAND {
- pg = pg.Where(q, cond.Value)
- } else {
- pg = pg.Or(q, cond.Value)
- }
- } else {
- if cond.Operator != "" && cond.Operator != rest.OperatorNot {
- err = rest.ErrorFiled(cond.Field, "Expected empty operator or not")
- }
- q := fmt.Sprintf("%s is %s null", CamelToSnake(cond.Field), cond.Operator)
- if i == 0 || cond.Logic == rest.LogicAND {
- pg = pg.Where(q, cond.Value)
- } else {
- pg = pg.Or(q, cond.Value)
- }
- }
- }
- // count
- if dbRes := pg.Count(&count); dbRes.Error != nil {
- err = rest.ErrorFiled("ErrDB", dbRes.Error.Error())
- return
- }
- // offset limit
- pg = pg.Offset(s.Offset).Limit(s.Limit)
- // orders
- for _, order := range s.Orders {
- pg = pg.Order(
- clause.OrderByColumn{
- Column: clause.Column{
- Name: CamelToSnake(order.Name),
- },
- Desc: !order.IsAsc,
- },
- )
- }
- if pg = pg.Find(res); pg.Error != nil {
- err = rest.ErrorFiled("ErrDB", pg.Error.Error())
- return
- }
- return
- }
|