-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterface.go
103 lines (83 loc) · 2 KB
/
interface.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package buzz
import (
"fmt"
"reflect"
)
type BuzzInterfaceValidateFunc[T any] func(T) error
type BuzzInterface[T any] struct {
name string
validateFuncs []BuzzInterfaceValidateFunc[T]
refType reflect.Type
nullable bool
}
func Interface[T any]() *BuzzInterface[T] {
refType := reflect.TypeOf(new(T)).Elem()
if refType.Kind() != reflect.Interface {
panic("noninterface is passed as generic parameter")
}
return &BuzzInterface[T]{
refType: refType,
nullable: true,
}
}
func (i *BuzzInterface[T]) Name() string {
return i.name
}
func (i *BuzzInterface[T]) Type() reflect.Type {
return i.refType
}
func (i *BuzzInterface[T]) Validate(v any) error {
if v == nil {
if i.nullable {
return nil
}
return notNullableFieldErr(i.name)
}
vT, ok := v.(T)
if !ok {
return fmt.Errorf(invalidTypeMsg, i.refType, v)
}
errAggr := NewFieldErrorAggregator()
for _, valFn := range i.validateFuncs {
if err := valFn(vT); err != nil {
if errAggr.Handle(err) != nil {
return err
}
}
}
return errAggr.OrNil()
}
func (i *BuzzInterface[T]) WithName(name string) BuzzField {
i.name = name
return i
}
func (i *BuzzInterface[T]) Clone() BuzzField {
return &BuzzInterface[T]{
name: i.name,
validateFuncs: i.validateFuncs,
refType: i.refType,
nullable: i.nullable,
}
}
func (i *BuzzInterface[T]) Nonnil() *BuzzInterface[T] {
i.nullable = false
return i
}
func (i *BuzzInterface[T]) MustBeType(typ T) *BuzzInterface[T] {
expectedType := reflect.TypeOf(typ)
i.registerValidateFunc(func(v T) error {
actualType := reflect.TypeOf(v)
if expectedType != actualType {
return MakeFieldError(i.name, "MustBeType", fmt.Sprintf(invalidTypeMsg, expectedType, v))
}
return nil
})
return i
}
func (i *BuzzInterface[T]) Custom(fn BuzzInterfaceValidateFunc[T]) *BuzzInterface[T] {
i.registerValidateFunc(fn)
return i
}
func (i *BuzzInterface[T]) registerValidateFunc(fn BuzzInterfaceValidateFunc[T]) {
i.validateFuncs = append(i.validateFuncs, fn)
}