-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_custom_argument_constraint_test.go
89 lines (72 loc) · 2.39 KB
/
example_custom_argument_constraint_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package validation_test
import (
"context"
"errors"
"fmt"
"github.com/muonsoft/validation"
"github.com/muonsoft/validation/validator"
)
type Brand struct {
Name string
}
type BrandRepository struct {
brands []Brand
}
func (repository *BrandRepository) FindByName(ctx context.Context, name string) ([]Brand, error) {
found := make([]Brand, 0)
for _, brand := range repository.brands {
if brand.Name == name {
found = append(found, brand)
}
}
return found, nil
}
// To create your own functional argument for validation simply create a function with
// a typed value and use the validation.This constructor.
func ValidBrand(brand *Brand, constraints ...validation.Constraint[*Brand]) validation.ValidatorArgument {
return validation.This[*Brand](brand, constraints...)
}
var ErrNotUniqueBrand = errors.New("not unique brand")
// UniqueBrandConstraint implements BrandConstraint.
type UniqueBrandConstraint struct {
brands *BrandRepository
}
func (c *UniqueBrandConstraint) Validate(ctx context.Context, validator *validation.Validator, brand *Brand) error {
// usually, you should ignore empty values
// to check for an empty value you should use it.NotBlankConstraint
if brand == nil {
return nil
}
brands, err := c.brands.FindByName(ctx, brand.Name)
// here you can return a service error so that the validation process
// is stopped immediately
if err != nil {
return err
}
if len(brands) == 0 {
return nil
}
// use the validator to build violation with translations
return validator.
BuildViolation(ctx, ErrNotUniqueBrand, `Brand with name "{{ name }}" already exists.`).
// you can inject parameter value to the message here
WithParameter("{{ name }}", brand.Name).
Create()
}
func ExampleThis_customArgumentConstraintValidator() {
repository := &BrandRepository{brands: []Brand{{"Apple"}, {"Orange"}}}
isUnique := &UniqueBrandConstraint{brands: repository}
brand := Brand{Name: "Apple"}
err := validator.Validate(
// you can pass here the context value to the validation context
context.WithValue(context.Background(), "key", "value"),
ValidBrand(&brand, isUnique),
// it is full equivalent of
// validation.This[*Brand](&brand, isUnique),
)
fmt.Println(err)
fmt.Println("errors.Is(err, ErrNotUniqueBrand) =", errors.Is(err, ErrNotUniqueBrand))
// Output:
// violation: "Brand with name "Apple" already exists."
// errors.Is(err, ErrNotUniqueBrand) = true
}