niki/validator/admin/benefactor/validator.go

130 lines
3.0 KiB
Go

package adminbenefactorvalidator
import (
"context"
"errors"
"fmt"
"slices"
"time"
"git.gocasts.ir/ebhomengo/niki/entity"
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 (
minLengthFirstName = 3
maxLengthFirstName = 40
minLengthLastName = 3
maxLengthLastName = 40
MaxLengthQuerySearch = 32
)
type Repository interface {
IsExistBenefactorByID(ctx context.Context, id uint) (bool, error)
}
type Validator struct {
repo Repository
}
func New(repo Repository) Validator {
return Validator{repo: repo}
}
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) doesBenefactorExist(ctx context.Context) validation.RuleFunc {
return func(value interface{}) error {
benefactor, ok := value.(uint)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
}
if isExist, err := v.repo.IsExistBenefactorByID(ctx, benefactor); !isExist || err != nil {
if err != nil {
return err
}
if !isExist {
return errors.New("benefactor is not exist")
}
}
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
}
}
func (v Validator) isDateValid(value interface{}) error {
date, ok := value.(params.Date)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
}
if date.After(time.Now()) {
return fmt.Errorf(errmsg.ErrorMsgInvalidInput)
}
return nil
}
func (v Validator) doesBenefactorStatusExist(value interface{}) error {
BenefactorStatus, ok := value.(entity.BenefactorStatus)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
}
if !BenefactorStatus.IsValid() {
return fmt.Errorf(errmsg.ErrorMsgInvalidBenefactorStatus)
}
return nil
}