forked from ebhomengo/niki
77 lines
2.0 KiB
Go
77 lines
2.0 KiB
Go
package agentkindboxvalidator
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
params "git.gocasts.ir/ebhomengo/niki/param"
|
|
"slices"
|
|
|
|
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
|
|
validation "github.com/go-ozzo/ozzo-validation/v4"
|
|
)
|
|
|
|
type Repository interface {
|
|
KindBoxExistForAgent(ctx context.Context, kindBoxID, agentID uint) (bool, error)
|
|
}
|
|
|
|
type Validator struct {
|
|
repo Repository
|
|
}
|
|
|
|
func New(repo Repository) Validator {
|
|
return Validator{repo: repo}
|
|
}
|
|
|
|
func (v Validator) doesKindBoxExistForAgent(ctx context.Context, agentID uint) validation.RuleFunc {
|
|
return func(value interface{}) error {
|
|
kindBoxID, ok := value.(uint)
|
|
if !ok {
|
|
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
|
|
}
|
|
exists, err := v.repo.KindBoxExistForAgent(ctx, kindBoxID, agentID)
|
|
if err != nil {
|
|
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
|
|
}
|
|
if !exists {
|
|
return fmt.Errorf(errmsg.ErrorMsgNotFound)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
}
|
|
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
|
|
}
|
|
}
|