forked from omissis/go-jsonschema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
107 lines (90 loc) · 2.34 KB
/
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
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
104
105
106
107
package generator
import (
"fmt"
"strings"
"github.com/Joh4nnesHartl/go-jsonschema/pkg/codegen"
)
type validator interface {
generate(out *codegen.Emitter)
desc() *validatorDesc
}
type validatorDesc struct {
hasError bool
beforeJSONUnmarshal bool
}
var (
_ validator = new(requiredValidator)
_ validator = new(nullTypeValidator)
_ validator = new(defaultValidator)
)
type requiredValidator struct {
jsonName string
}
func (v *requiredValidator) generate(out *codegen.Emitter) {
out.Println(`if v, ok := %s["%s"]; !ok || v == nil {`, varNameRawMap, v.jsonName)
out.Indent(1)
out.Println(`return fmt.Errorf("field %s: required")`, v.jsonName)
out.Indent(-1)
out.Println("}")
}
func (v *requiredValidator) desc() *validatorDesc {
return &validatorDesc{
hasError: true,
beforeJSONUnmarshal: true,
}
}
type nullTypeValidator struct {
jsonName string
fieldName string
arrayDepth int
}
func (v *nullTypeValidator) generate(out *codegen.Emitter) {
value := fmt.Sprintf("%s.%s", varNamePlainStruct, v.fieldName)
fieldName := v.jsonName
var indexes []string
for i := 0; i < v.arrayDepth; i++ {
index := fmt.Sprintf("i%d", i)
indexes = append(indexes, index)
out.Println(`for %s := range %s {`, index, value)
value += fmt.Sprintf("[%s]", index)
fieldName += "[%d]"
out.Indent(1)
}
fieldName = fmt.Sprintf(`"%s"`, fieldName)
if len(indexes) > 0 {
fieldName = fmt.Sprintf(`fmt.Sprinf(%s, %s)`, fieldName, strings.Join(indexes, ", "))
}
out.Println(`if %s != nil {`, value)
out.Indent(1)
out.Println(`return fmt.Errorf("field %%s: must be null", %s)`, fieldName)
out.Indent(-1)
out.Println("}")
for i := 0; i < v.arrayDepth; i++ {
out.Indent(-1)
out.Println("}")
}
}
func (v *nullTypeValidator) desc() *validatorDesc {
return &validatorDesc{
hasError: true,
beforeJSONUnmarshal: false,
}
}
type defaultValidator struct {
jsonName string
fieldName string
defaultValue string
}
func (v *defaultValidator) generate(out *codegen.Emitter) {
out.Println(`if v, ok := %s["%s"]; !ok || v == nil {`, varNameRawMap, v.jsonName)
out.Indent(1)
out.Println(`%s.%s = %s`, varNamePlainStruct, v.fieldName, v.defaultValue)
out.Indent(-1)
out.Println("}")
}
func (v *defaultValidator) desc() *validatorDesc {
return &validatorDesc{
hasError: false,
beforeJSONUnmarshal: false,
}
}