search_query_set.go 1.4 KB
package query

import (
	"fmt"
	"github.com/beego/beego/v2/adapter/utils"
	"reflect"
	"strings"

	"github.com/beego/beego/v2/core/validation"
)

type SearchQuerySetQuery struct {
	Type       string `cname:"类型" json:"type" valid:"Required"`
	Flag       string `cname:"标识" json:"flag"`
	MatchName  string `cname:"匹配名称" json:"matchName"`
	SortByName string `json:"sortByName"`
	SortByTime string `json:"sortByTime"`
}

func (searchQuerySetQuery *SearchQuerySetQuery) Valid(validation *validation.Validation) {
	optionsValues := []string{"asc", "desc"}
	if searchQuerySetQuery.SortByName != "" && !utils.InSlice(strings.ToLower(searchQuerySetQuery.SortByName), optionsValues) {
		validation.Error("排序值有误 ASC|DESC")
	}
	if searchQuerySetQuery.SortByTime != "" && !utils.InSlice(strings.ToLower(searchQuerySetQuery.SortByTime), optionsValues) {
		validation.Error("排序值有误 ASC|DESC")
	}
}

func (searchQuerySetQuery *SearchQuerySetQuery) ValidateQuery() error {
	valid := validation.Validation{}
	b, err := valid.Valid(searchQuerySetQuery)
	if err != nil {
		return err
	}
	if !b {
		elem := reflect.TypeOf(searchQuerySetQuery).Elem()
		for _, validErr := range valid.Errors {
			field, isExist := elem.FieldByName(validErr.Field)
			if isExist {
				return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
			} else {
				return fmt.Errorf(validErr.Message)
			}
		}
	}
	return nil
}