field_optional_values.go 1.3 KB
package command

import (
	"fmt"
	"reflect"
	"strings"

	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"

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

type FieldOptionalValuesCommand struct {
	ObjectType string            `cname:"对象类型" json:"objectType" valid:"Required"`
	ObjectId   int               `cname:"对象Id标识" json:"objectId" valid:"Required"`
	Field      domain.Field      `cname:"列" json:"field" valid:"Required"`
	Match      string            `cname:"匹配内容" json:"match"`
	PageNumber int               `json:"pageNumber"`
	PageSize   int               `json:"pageSize"`
	Condition  *domain.Condition `json:"condition"`
}

func (cmd *FieldOptionalValuesCommand) Valid(validation *validation.Validation) {
	if cmd.PageSize == 0 {
		cmd.PageNumber = 1
		cmd.PageSize = 2000
	}
}

func (cmd *FieldOptionalValuesCommand) ValidateCommand() error {
	valid := validation.Validation{}
	b, err := valid.Valid(cmd)
	if err != nil {
		return err
	}
	if !b {
		elem := reflect.TypeOf(cmd).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
}