-
Notifications
You must be signed in to change notification settings - Fork 34
/
util_validator.go
49 lines (42 loc) · 1.06 KB
/
util_validator.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
package transformer
import (
"context"
"github.com/machinefi/w3bstream/pkg/depends/kit/validator"
"github.com/machinefi/w3bstream/pkg/depends/x/reflectx"
"github.com/machinefi/w3bstream/pkg/depends/x/typesx"
)
type MayValidator interface {
NewValidator(context.Context, typesx.Type) (validator.Validator, error)
}
type WithNamedByTag interface {
NamedByTag() string
}
func NewValidator(
ctx context.Context,
ft typesx.Type,
tags map[string]reflectx.StructTag,
omitempty bool,
tsfm Transformer,
) (validator.Validator, error) {
if with, ok := tsfm.(WithNamedByTag); ok {
if tagKey := with.NamedByTag(); tagKey != "" {
ctx = validator.ContextWithTagKey(ctx, tagKey)
}
}
if t, ok := tsfm.(MayValidator); ok {
return t.NewValidator(ctx, ft)
}
compiler := validator.FactoryFromContext(ctx)
return compiler.Compile(
ctx,
[]byte(tags[validator.TagValidate]),
ft, func(rule validator.Modifier) {
if omitempty {
rule.SetOptional(true)
}
if dftv, ok := tags[validator.TagDefault]; ok {
rule.SetDefaultValue([]byte(dftv))
}
},
)
}