forked from ebhomengo/niki
71 lines
1.7 KiB
Go
71 lines
1.7 KiB
Go
package adminbenefactorvalidator
|
|
|
|
import (
|
|
"fmt"
|
|
"slices"
|
|
|
|
params "git.gocasts.ir/ebhomengo/niki/param"
|
|
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
|
|
validation "github.com/go-ozzo/ozzo-validation/v4"
|
|
)
|
|
|
|
const (
|
|
MaxLengthQuerySearch = 32
|
|
)
|
|
|
|
type Validator struct{}
|
|
|
|
func New() Validator {
|
|
return Validator{}
|
|
}
|
|
|
|
func (v Validator) AreSortFieldsValid(validSortFields []string) validation.RuleFunc {
|
|
return func(value interface{}) error {
|
|
sort, ok := value.(params.SortRequest)
|
|
if !ok {
|
|
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
|
|
}
|
|
if sort.Field == "" && sort.Direction != "" {
|
|
return fmt.Errorf(errmsg.ErrorMsgSortFieldIsRequired)
|
|
}
|
|
if sort.Direction != "" && sort.Direction != params.AscSortDirection && sort.Direction != params.DescSortDirection {
|
|
return fmt.Errorf(errmsg.ErrorMsgSortDirectionShouldBeAscOrDesc)
|
|
}
|
|
if sort.Field != "" && !slices.Contains(validSortFields, sort.Field) {
|
|
return fmt.Errorf(errmsg.ErrorMsgSortFieldIsNotValid)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func (v Validator) AreFilterFieldsValid(validFilters []string) validation.RuleFunc {
|
|
return func(value interface{}) error {
|
|
filters, ok := value.(params.FilterRequest)
|
|
if !ok {
|
|
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
|
|
}
|
|
for filter := range filters {
|
|
if !slices.Contains(validFilters, filter) {
|
|
return fmt.Errorf(errmsg.ErrorMsgFiltersAreNotValid)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func (v Validator) AreSearchValid() validation.RuleFunc {
|
|
return func(value interface{}) error {
|
|
search, ok := value.(params.SearchRequest)
|
|
if !ok {
|
|
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
|
|
}
|
|
if len(search.Query) > MaxLengthQuerySearch {
|
|
return fmt.Errorf(errmsg.ErrorMsgInvalidInput)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
}
|