-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathexample_vocab_uniquekeys_test.go
134 lines (115 loc) · 2.43 KB
/
example_vocab_uniquekeys_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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package jsonschema_test
import (
"fmt"
"log"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
"golang.org/x/text/message"
)
// SchemaExt --
type uniqueKeys struct {
pname string
}
func (s *uniqueKeys) Validate(ctx *jsonschema.ValidatorContext, v any) {
arr, ok := v.([]any)
if !ok {
return
}
var keys []any
for _, item := range arr {
obj, ok := item.(map[string]any)
if !ok {
continue
}
key, ok := obj[s.pname]
if ok {
keys = append(keys, key)
}
}
i, j, err := ctx.Duplicates(keys)
if err != nil {
ctx.AddErr(err)
return
}
if i != -1 {
ctx.AddError(&UniqueKeys{Key: s.pname, Duplicates: []int{i, j}})
}
}
// Vocab --
func uniqueKeysVocab() *jsonschema.Vocabulary {
url := "http://example.com/meta/unique-keys"
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"properties": {
"uniqueKeys": { "type": "string" }
}
}`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
if err := c.AddResource(url, schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile(url)
if err != nil {
log.Fatal(err)
}
return &jsonschema.Vocabulary{
URL: url,
Schema: sch,
Compile: compileUniqueKeys,
}
}
func compileUniqueKeys(ctx *jsonschema.CompilerContext, obj map[string]any) (jsonschema.SchemaExt, error) {
v, ok := obj["uniqueKeys"]
if !ok {
return nil, nil
}
s, ok := v.(string)
if !ok {
return nil, nil
}
return &uniqueKeys{pname: s}, nil
}
// ErrorKind --
type UniqueKeys struct {
Key string
Duplicates []int
}
func (*UniqueKeys) KeywordPath() []string {
return []string{"uniqueKeys"}
}
func (k *UniqueKeys) LocalizedString(p *message.Printer) string {
return p.Sprintf("items at %d and %d have same %s", k.Duplicates[0], k.Duplicates[1], k.Key)
}
// Example --
func Example_vocab_uniquekeys() {
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"uniqueKeys": "id"
}`))
if err != nil {
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(strings.NewReader(`[
{ "id": 1, "name": "alice" },
{ "id": 2, "name": "bob" },
{ "id": 1, "name": "scott" }
]`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
c.AssertVocabs()
c.RegisterVocabulary(uniqueKeysVocab())
if err := c.AddResource("schema.json", schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("schema.json")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
// Output:
// valid: false
}