forked from wundergraph/graphql-go-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonschema.go
414 lines (358 loc) · 8.88 KB
/
jsonschema.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package graphqljsonschema
import (
"context"
"encoding/json"
"fmt"
"github.com/buger/jsonparser"
"github.com/santhosh-tekuri/jsonschema/v5"
"github.com/wundergraph/graphql-go-tools/v2/pkg/ast"
)
type options struct {
overrides map[string]JsonSchema
path []string
}
type Option func(opts *options)
func WithOverrides(overrides map[string]JsonSchema) Option {
return func(opts *options) {
opts.overrides = overrides
}
}
func WithPath(path []string) Option {
return func(opts *options) {
opts.path = path
}
}
func FromTypeRef(operation, definition *ast.Document, typeRef int, opts ...Option) JsonSchema {
appliedOptions := &options{}
for _, opt := range opts {
opt(appliedOptions)
}
var resolver *fromTypeRefResolver
if len(appliedOptions.overrides) > 0 {
resolver = &fromTypeRefResolver{
overrides: appliedOptions.overrides,
}
} else {
resolver = &fromTypeRefResolver{
overrides: map[string]JsonSchema{},
}
}
jsonSchema := resolver.fromTypeRef(operation, definition, typeRef)
return resolveJsonSchemaPath(jsonSchema, appliedOptions.path)
}
func resolveJsonSchemaPath(jsonSchema JsonSchema, path []string) JsonSchema {
switch typedJsonSchema := jsonSchema.(type) {
case Object:
for i := 0; i < len(path); i++ {
propertyJsonSchema, exists := typedJsonSchema.Properties[path[i]]
if !exists {
return jsonSchema
}
jsonSchema = propertyJsonSchema
}
}
return jsonSchema
}
type fromTypeRefResolver struct {
overrides map[string]JsonSchema
defs *map[string]JsonSchema
}
func (r *fromTypeRefResolver) fromTypeRef(operation, definition *ast.Document, typeRef int) JsonSchema {
t := operation.Types[typeRef]
nonNull := false
if operation.TypeIsNonNull(typeRef) {
t = operation.Types[t.OfType]
nonNull = true
}
switch t.TypeKind {
case ast.TypeKindList:
var defs map[string]JsonSchema
isRoot := false
if r.defs == nil {
defs = make(map[string]JsonSchema, 48)
r.defs = &defs
isRoot = true
}
itemSchema := r.fromTypeRef(operation, definition, t.OfType)
arr := NewArray(itemSchema, nonNull)
if isRoot {
arr.Defs = defs
}
return arr
case ast.TypeKindNonNull:
panic("Should not be able to have multiple levels of non-null")
case ast.TypeKindNamed:
name := operation.Input.ByteSliceString(t.Name)
if schema, ok := r.overrides[name]; ok {
return schema
}
typeDefinitionNode, ok := definition.Index.FirstNodeByNameStr(name)
if !ok {
return NewAny()
}
if typeDefinitionNode.Kind == ast.NodeKindEnumTypeDefinition {
return NewString(nonNull)
}
if typeDefinitionNode.Kind == ast.NodeKindScalarTypeDefinition {
switch name {
case "Boolean":
return NewBoolean(nonNull)
case "String":
return NewString(nonNull)
case "ID":
return NewID(nonNull)
case "Int":
return NewInteger(nonNull)
case "Float":
return NewNumber(nonNull)
case "_Any":
return NewObjectAny(nonNull)
default:
return NewAny()
}
}
object := NewObject(nonNull)
isRootObject := false
if r.defs == nil {
isRootObject = true
object.Defs = make(map[string]JsonSchema, 48)
r.defs = &object.Defs
}
if !isRootObject {
if _, exists := (*r.defs)[name]; exists {
return NewRef(name)
}
(*r.defs)[name] = object
}
if node, ok := definition.Index.FirstNodeByNameStr(name); ok {
switch node.Kind {
case ast.NodeKindInputObjectTypeDefinition:
for _, ref := range definition.InputObjectTypeDefinitions[node.Ref].InputFieldsDefinition.Refs {
fieldName := definition.Input.ByteSliceString(definition.InputValueDefinitions[ref].Name)
fieldType := definition.InputValueDefinitions[ref].Type
fieldSchema := r.fromTypeRef(definition, definition, fieldType)
object.Properties[fieldName] = fieldSchema
if definition.TypeIsNonNull(fieldType) {
object.Required = append(object.Required, fieldName)
}
}
case ast.NodeKindObjectTypeDefinition:
for _, ref := range definition.ObjectTypeDefinitions[node.Ref].FieldsDefinition.Refs {
fieldName := definition.Input.ByteSliceString(definition.FieldDefinitions[ref].Name)
fieldType := definition.FieldDefinitions[ref].Type
fieldSchema := r.fromTypeRef(definition, definition, fieldType)
object.Properties[fieldName] = fieldSchema
if definition.TypeIsNonNull(fieldType) {
object.Required = append(object.Required, fieldName)
}
}
}
}
if !isRootObject {
(*r.defs)[name] = object
return NewRef(name)
}
return object
}
return NewObject(nonNull)
}
type Validator struct {
schema *jsonschema.Schema
}
func NewValidatorFromSchema(schema JsonSchema) (*Validator, error) {
s, err := json.Marshal(schema)
if err != nil {
return nil, err
}
return NewValidatorFromString(string(s))
}
func MustNewValidatorFromSchema(schema JsonSchema) *Validator {
s, err := json.Marshal(schema)
if err != nil {
panic(err)
}
return MustNewValidatorFromString(string(s))
}
func NewValidatorFromString(schema string) (*Validator, error) {
sch, err := jsonschema.CompileString("schema.json", schema)
if err != nil {
return nil, err
}
return &Validator{
schema: sch,
}, nil
}
func MustNewValidatorFromString(schema string) *Validator {
validator, err := NewValidatorFromString(schema)
if err != nil {
panic(err)
}
return validator
}
func (v *Validator) Validate(ctx context.Context, inputJSON []byte) error {
var value interface{}
if err := json.Unmarshal(inputJSON, &value); err != nil {
return err
}
if err := v.schema.Validate(value); err != nil {
return err
}
return nil
}
func TopLevelType(schema string) (jsonparser.ValueType, error) {
sch, err := jsonschema.CompileString("schema.json", schema)
if err != nil {
return jsonparser.Unknown, err
}
switch sch.Types[0] {
case "boolean":
return jsonparser.Boolean, nil
case "string":
return jsonparser.String, nil
case "object":
return jsonparser.Object, nil
case "number":
return jsonparser.Number, nil
case "integer":
return jsonparser.Number, nil
case "null":
return jsonparser.Null, nil
case "array":
return jsonparser.Array, nil
default:
return jsonparser.NotExist, nil
}
}
type Kind int
const (
StringKind Kind = iota + 1
NumberKind
BooleanKind
IntegerKind
ObjectKind
ArrayKind
AnyKind
IDKind
RefKind
)
func maybeAppendNull(nonNull bool, types ...string) []string {
if nonNull {
return types
}
return append(types, "null")
}
type JsonSchema interface {
Kind() Kind
}
type Any struct{}
func NewAny() Any {
return Any{}
}
func (a Any) Kind() Kind {
return AnyKind
}
type String struct {
Type []string `json:"type"`
}
func (String) Kind() Kind {
return StringKind
}
func NewString(nonNull bool) String {
return String{
Type: maybeAppendNull(nonNull, "string"),
}
}
type ID struct {
Type []string `json:"type"`
}
func (ID) Kind() Kind {
return IDKind
}
func NewID(nonNull bool) ID {
return ID{
Type: maybeAppendNull(nonNull, "string", "integer"),
}
}
type Boolean struct {
Type []string `json:"type"`
}
func (Boolean) Kind() Kind {
return BooleanKind
}
func NewBoolean(nonNull bool) Boolean {
return Boolean{
Type: maybeAppendNull(nonNull, "boolean"),
}
}
type Number struct {
Type []string `json:"type"`
}
func NewNumber(nonNull bool) Number {
return Number{
Type: maybeAppendNull(nonNull, "number"),
}
}
func (Number) Kind() Kind {
return NumberKind
}
type Integer struct {
Type []string `json:"type"`
}
func (Integer) Kind() Kind {
return IntegerKind
}
func NewInteger(nonNull bool) Integer {
return Integer{
Type: maybeAppendNull(nonNull, "integer"),
}
}
type Ref struct {
Ref string `json:"$ref"`
}
func (Ref) Kind() Kind {
return RefKind
}
func NewRef(definitionName string) Ref {
return Ref{
Ref: fmt.Sprintf("#/$defs/%s", definitionName),
}
}
type Object struct {
Type []string `json:"type"`
Properties map[string]JsonSchema `json:"properties,omitempty"`
Required []string `json:"required,omitempty"`
AdditionalProperties bool `json:"additionalProperties"`
Defs map[string]JsonSchema `json:"$defs,omitempty"`
}
func (Object) Kind() Kind {
return ObjectKind
}
func NewObject(nonNull bool) Object {
return Object{
Type: maybeAppendNull(nonNull, "object"),
Properties: map[string]JsonSchema{},
AdditionalProperties: false,
}
}
func NewObjectAny(nonNull bool) Object {
return Object{
Type: maybeAppendNull(nonNull, "object"),
Properties: map[string]JsonSchema{},
AdditionalProperties: true,
}
}
type Array struct {
Type []string `json:"type"`
Items JsonSchema `json:"items"`
MinItems *int `json:"minItems,omitempty"`
Defs map[string]JsonSchema `json:"$defs,omitempty"`
}
func (Array) Kind() Kind {
return ArrayKind
}
func NewArray(itemSchema JsonSchema, nonNull bool) Array {
return Array{
Type: maybeAppendNull(nonNull, "array"),
Items: itemSchema,
}
}