2024-07-13 12:33:07 +00:00
|
|
|
package agentkindboxvalidator
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2024-09-15 07:36:09 +00:00
|
|
|
params "git.gocasts.ir/ebhomengo/niki/param"
|
|
|
|
"slices"
|
2024-07-24 23:45:04 +00:00
|
|
|
|
2024-07-13 12:33:07 +00:00
|
|
|
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
|
2024-08-01 10:20:18 +00:00
|
|
|
validation "github.com/go-ozzo/ozzo-validation/v4"
|
2024-07-13 12:33:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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}
|
|
|
|
}
|
|
|
|
|
2024-08-01 10:20:18 +00:00
|
|
|
func (v Validator) doesKindBoxExistForAgent(ctx context.Context, agentID uint) validation.RuleFunc {
|
2024-07-13 12:33:07 +00:00
|
|
|
return func(value interface{}) error {
|
|
|
|
kindBoxID, ok := value.(uint)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
|
|
|
|
}
|
2024-08-01 10:20:18 +00:00
|
|
|
exists, err := v.repo.KindBoxExistForAgent(ctx, kindBoxID, agentID)
|
2024-07-13 12:33:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
|
|
|
|
}
|
|
|
|
if !exists {
|
|
|
|
return fmt.Errorf(errmsg.ErrorMsgNotFound)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2024-09-15 07:36:09 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|