-
Notifications
You must be signed in to change notification settings - Fork 1
/
object.go
81 lines (70 loc) · 1.43 KB
/
object.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
package valval
type M map[string]Validator
type ObjectValidatorFunc func(content map[string]interface{}) error
type ObjectValidator struct {
vMap M
selfVfuncs []ObjectValidatorFunc
}
func (ov *ObjectValidator) Validate(val interface{}) error {
uw := unwrapPtr(val)
if uw == nil {
return nil
}
valMap, err := obj2Map(uw)
if err != nil {
return typeMissmatchError("object")
}
// inner
if err := ov.checkInner(valMap); err != nil {
return err
}
// self
if err := ov.checkSelf(valMap); err != nil {
return err
}
return nil
}
func (ov *ObjectValidator) checkInner(valMap map[string]objField) error {
var errs []*objectErrorField
for k, fv := range ov.vMap {
fValue := valMap[k]
err := fv.Validate(fValue.value)
if err != nil {
errs = append(errs, &objectErrorField{
Name: k,
Err: err,
Tag: fValue.tag,
})
}
}
if errs != nil {
ret := objectError(errs)
return &ret
}
return nil
}
func (ov *ObjectValidator) checkSelf(valMap map[string]objField) error {
errs := []error{}
for _, svf := range ov.selfVfuncs {
err := svf(fieldMap2objMap(valMap))
if err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
ret := valueError(errs)
return &ret
}
return nil
}
func (ov *ObjectValidator) Self(vfs ...ObjectValidatorFunc) *ObjectValidator {
// copy
newOv := *ov
newOv.selfVfuncs = vfs
return &newOv
}
func Object(m M) *ObjectValidator {
return &ObjectValidator{
vMap: m,
}
}