| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- package queryreq
-
- // SortParam 排序参数
- type SortParam struct {
- Field string `json:"field"` // 前端字段名
- Order string `json:"order"` // asc/desc
- }
-
- // FilterParam 筛选参数
- type FilterParam struct {
- Field string `json:"field"` // 前端字段名
- Operator Operator `json:"operator"` // 运算符枚举
- Value interface{} `json:"value"` // 值(支持多种类型)
- }
-
- // QueryRequest 通用查询请求
- type QueryRequest struct {
- Page int `json:"page"` // 页码(从0开始)
- PageSize int `json:"pageSize"` // 每页大小
- Sort []SortParam `json:"sort,omitempty"`
- Filter []FilterParam `json:"filter,omitempty"`
- }
-
- // Validate 验证查询请求参数
- func (q *QueryRequest) Validate() error {
- // 验证分页参数
- if q.Page < 0 {
- q.Page = 0
- }
- if q.PageSize <= 0 {
- q.PageSize = 10
- } else if q.PageSize > 1000 {
- q.PageSize = 1000 // 限制最大页大小
- }
-
- // 验证排序参数
- for i := range q.Sort {
- if q.Sort[i].Order != "asc" && q.Sort[i].Order != "desc" {
- q.Sort[i].Order = "asc" // 默认升序
- }
- }
-
- // 验证筛选参数
- for i := range q.Filter {
- if !q.Filter[i].Operator.IsValid() {
- // 无效运算符,移除该筛选条件
- q.Filter = append(q.Filter[:i], q.Filter[i+1:]...)
- continue
- }
- }
-
- return nil
- }
-
- // GetOffset 计算分页偏移量
- func (q *QueryRequest) GetOffset() int {
- return q.Page * q.PageSize
- }
-
- // GetLimit 获取分页限制
- func (q *QueryRequest) GetLimit() int {
- return q.PageSize
- }
|