-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathvariables_schema.go
More file actions
592 lines (506 loc) · 19.6 KB
/
variables_schema.go
File metadata and controls
592 lines (506 loc) · 19.6 KB
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
package jsonschema
import (
"fmt"
"github.com/wundergraph/graphql-go-tools/v2/pkg/ast"
"github.com/wundergraph/graphql-go-tools/v2/pkg/astvisitor"
"github.com/wundergraph/graphql-go-tools/v2/pkg/operationreport"
)
// VariablesSchemaBuilder creates a unified JSON schema for the variables of a GraphQL operation
type VariablesSchemaBuilder struct {
operationDocument *ast.Document
definitionDocument *ast.Document
schema *JsonSchema
report *operationreport.Report
// Track recursion depth for each type to handle recursive types
recursionTracker map[string]int
maxRecursionDepth int
}
// Ensure VariablesSchemaBuilder implements the necessary astvisitor interfaces
var (
_ astvisitor.EnterDocumentVisitor = (*VariablesSchemaBuilder)(nil)
_ astvisitor.EnterVariableDefinitionVisitor = (*VariablesSchemaBuilder)(nil)
)
// NewVariablesSchemaBuilder creates a new VariablesSchemaBuilder with default settings
func NewVariablesSchemaBuilder(operationDocument, definitionDocument *ast.Document) *VariablesSchemaBuilder {
return NewVariablesSchemaBuilderWithOptions(operationDocument, definitionDocument, 3)
}
// NewVariablesSchemaBuilderWithOptions creates a new VariablesSchemaBuilder with custom options
func NewVariablesSchemaBuilderWithOptions(operationDocument, definitionDocument *ast.Document, maxRecursionDepth int) *VariablesSchemaBuilder {
return &VariablesSchemaBuilder{
operationDocument: operationDocument,
definitionDocument: definitionDocument,
schema: NewObjectSchema(),
report: &operationreport.Report{},
recursionTracker: make(map[string]int),
maxRecursionDepth: maxRecursionDepth,
}
}
// EnterDocument implements the astvisitor.EnterDocumentVisitor interface
func (v *VariablesSchemaBuilder) EnterDocument(operation, definition *ast.Document) {
if len(operation.OperationDefinitions) == 0 {
return
}
v.schema = NewObjectSchema()
v.recursionTracker = make(map[string]int) // Reset recursion tracker for each build
// Extract descriptions from root fields
var descriptions []string
operationDefinition := operation.OperationDefinitions[0]
// Process SelectionSet to extract field descriptions
if operationDefinition.HasSelections {
selectionSetRef := operationDefinition.SelectionSet
for _, selectionRef := range operation.SelectionSets[selectionSetRef].SelectionRefs {
selection := operation.Selections[selectionRef]
if selection.Kind == ast.SelectionKindField {
fieldName := operation.FieldNameString(selection.Ref)
// Look up field in schema definition to get description
operationType := operationDefinition.OperationType
var rootTypeName string
// Determine root type based on operation type
switch operationType {
case ast.OperationTypeQuery:
rootTypeName = "Query"
case ast.OperationTypeMutation:
rootTypeName = "Mutation"
case ast.OperationTypeSubscription:
rootTypeName = "Subscription"
default:
v.report.AddInternalError(fmt.Errorf("unsupported operation type %q", operationType))
return
}
rootType, exists := definition.Index.FirstNodeByNameStr(rootTypeName)
if exists && rootType.Kind == ast.NodeKindObjectTypeDefinition {
// Find the field in the root type
for _, fieldDefRef := range definition.ObjectTypeDefinitions[rootType.Ref].FieldsDefinition.Refs {
fieldDefName := definition.FieldDefinitionNameString(fieldDefRef)
// Match field name
if fieldDefName == fieldName && definition.FieldDefinitions[fieldDefRef].Description.IsDefined {
description := definition.FieldDefinitionDescriptionString(fieldDefRef)
if description != "" {
descriptions = append(descriptions, description)
}
break
}
}
}
}
}
}
// Set concatenated descriptions on root schema if any were found
if len(descriptions) > 0 {
v.schema.Description = ""
for i, desc := range descriptions {
if i > 0 {
v.schema.Description += " "
}
v.schema.Description += desc
}
}
}
// EnterVariableDefinition implements the astvisitor.EnterVariableDefinitionVisitor interface
func (v *VariablesSchemaBuilder) EnterVariableDefinition(ref int) {
varName := v.operationDocument.VariableDefinitionNameString(ref)
typeRef := v.operationDocument.VariableDefinitions[ref].Type
// Convert type to schema starting from the operation document
varSchema := v.processOperationTypeRef(typeRef)
// Skip this variable if we reached maximum recursion depth
if varSchema == nil {
return
}
// Add variable to required list if it's non-nullable
if v.operationDocument.TypeIsNonNull(typeRef) {
v.schema.Required = append(v.schema.Required, varName)
}
// Set variable description: use the variable's own description if present (AC2),
// otherwise fall back to the field argument description from the schema (AC3)
if v.operationDocument.VariableDefinitions[ref].Description.IsDefined {
varSchema.Description = v.operationDocument.VariableDefinitionDescriptionString(ref)
} else {
// Fall back to argument description from schema definition
if desc := v.findArgumentDescriptionForVariable(varName); desc != "" {
varSchema.Description = desc
}
}
// Set default value if exists
if v.operationDocument.VariableDefinitionHasDefaultValue(ref) {
defaultValue := v.operationDocument.VariableDefinitionDefaultValue(ref)
varSchema.Default = v.convertOperationValueToNative(defaultValue)
}
// Force top-level object fields to be not nullable (Nullable=false) so they can't be null
// This ensures they appear as empty objects at minimum
if varSchema.Type == TypeObject {
// Setting Nullable to false means the field can't be null
// Since the nullable field is only included when true, this effectively removes it
// from the output JSON, which is what we want
varSchema.Nullable = false
}
// Add variable to schema
v.schema.Properties[varName] = varSchema
}
// findArgumentDescriptionForVariable looks up the argument description from the schema definition
// for a variable by matching it to field arguments in the operation's root selection set.
func (v *VariablesSchemaBuilder) findArgumentDescriptionForVariable(varName string) string {
if len(v.operationDocument.OperationDefinitions) == 0 {
return ""
}
operationDef := v.operationDocument.OperationDefinitions[0]
if !operationDef.HasSelections {
return ""
}
// Determine root type name
var rootTypeName string
switch operationDef.OperationType {
case ast.OperationTypeQuery:
rootTypeName = "Query"
case ast.OperationTypeMutation:
rootTypeName = "Mutation"
case ast.OperationTypeSubscription:
rootTypeName = "Subscription"
default:
return ""
}
rootType, exists := v.definitionDocument.Index.FirstNodeByNameStr(rootTypeName)
if !exists || rootType.Kind != ast.NodeKindObjectTypeDefinition {
return ""
}
// Iterate through root fields in the operation's selection set
selectionSetRef := operationDef.SelectionSet
for _, selectionRef := range v.operationDocument.SelectionSets[selectionSetRef].SelectionRefs {
selection := v.operationDocument.Selections[selectionRef]
if selection.Kind != ast.SelectionKindField {
continue
}
fieldRef := selection.Ref
// Check if this field has arguments referencing our variable
if !v.operationDocument.FieldHasArguments(fieldRef) {
continue
}
for _, argRef := range v.operationDocument.Fields[fieldRef].Arguments.Refs {
argValue := v.operationDocument.ArgumentValue(argRef)
if argValue.Kind != ast.ValueKindVariable {
continue
}
argVarName := v.operationDocument.VariableValueNameString(argValue.Ref)
if argVarName != varName {
continue
}
// Found the argument that references this variable.
// Look up the corresponding argument definition in the schema.
argName := v.operationDocument.ArgumentNameString(argRef)
fieldName := v.operationDocument.FieldNameString(fieldRef)
// Find this field in the root type definition
for _, fieldDefRef := range v.definitionDocument.ObjectTypeDefinitions[rootType.Ref].FieldsDefinition.Refs {
if v.definitionDocument.FieldDefinitionNameString(fieldDefRef) != fieldName {
continue
}
// Find the argument definition
for _, argDefRef := range v.definitionDocument.FieldDefinitionArgumentsDefinitions(fieldDefRef) {
if v.definitionDocument.InputValueDefinitionNameString(argDefRef) == argName {
if v.definitionDocument.InputValueDefinitions[argDefRef].Description.IsDefined {
return v.definitionDocument.InputValueDefinitionDescriptionString(argDefRef)
}
}
}
}
}
}
return ""
}
// GetSchema returns the built schema
func (v *VariablesSchemaBuilder) GetSchema() *JsonSchema {
// If we have required fields, the root schema cannot be nullable
if len(v.schema.Required) > 0 {
v.schema.Nullable = false
}
return v.schema
}
// GetReport returns the report containing any errors
func (v *VariablesSchemaBuilder) GetReport() *operationreport.Report {
return v.report
}
// Build traverses the operation and builds a unified JSON schema for its variables
func (v *VariablesSchemaBuilder) Build() (*JsonSchema, error) {
// Create a new walker for AST traversal
walker := astvisitor.NewDefaultWalker()
// Register this builder as a visitor
walker.RegisterEnterDocumentVisitor(v)
walker.RegisterEnterVariableDefinitionVisitor(v)
// Walk the AST
walker.Walk(v.operationDocument, v.definitionDocument, v.report)
if v.report.HasErrors() {
return nil, fmt.Errorf("%s", v.report.Error())
}
return v.GetSchema(), nil
}
// processOperationTypeRef processes a type reference from the operation document
func (v *VariablesSchemaBuilder) processOperationTypeRef(typeRef int) *JsonSchema {
switch v.operationDocument.Types[typeRef].TypeKind {
case ast.TypeKindNonNull:
ofType := v.operationDocument.Types[typeRef].OfType
schema := v.processOperationTypeRef(ofType)
if schema == nil {
return nil
}
// Non-null types are not nullable
schema.Nullable = false
return schema
case ast.TypeKindList:
ofType := v.operationDocument.Types[typeRef].OfType
itemSchema := v.processOperationTypeRef(ofType)
if itemSchema == nil {
return nil
}
// If we're not in a non-null context, list is nullable
schema := NewArraySchema(itemSchema)
schema.Nullable = true
return schema
case ast.TypeKindNamed:
typeName := v.operationDocument.TypeNameString(typeRef)
schema := v.processTypeByName(typeName)
if schema != nil {
// If we're not in a non-null context, named type is nullable
schema.Nullable = true
}
return schema
}
return nil
}
// processTypeByName processes a type by its name, looking it up in the definition document
func (v *VariablesSchemaBuilder) processTypeByName(typeName string) *JsonSchema {
// Handle built-in scalars
switch typeName {
case "String", "ID":
return NewStringSchema()
case "Int":
return NewIntegerSchema()
case "Float":
return NewNumberSchema()
case "Boolean":
return NewBooleanSchema()
}
// For custom types, look up in the definition document
node, exists := v.definitionDocument.Index.FirstNodeByNameStr(typeName)
if !exists {
v.report.AddInternalError(fmt.Errorf("type %s is not defined", typeName))
return NewObjectSchema()
}
var shouldCleanupTracker bool
// Check recursion depth for complex types that could be recursive
if node.Kind == ast.NodeKindEnumTypeDefinition || node.Kind == ast.NodeKindInputObjectTypeDefinition {
currentDepth, exists := v.recursionTracker[typeName]
if exists {
// We've seen this type before
currentDepth++
v.recursionTracker[typeName] = currentDepth
shouldCleanupTracker = true
// If we've hit our recursion limit, return nil to signal field removal
if currentDepth > v.maxRecursionDepth {
return nil
}
} else {
// First time seeing this type
v.recursionTracker[typeName] = 1
shouldCleanupTracker = true
}
}
// Process the type based on its kind
var schema *JsonSchema
switch node.Kind {
case ast.NodeKindEnumTypeDefinition:
schema = v.processEnumType(node)
case ast.NodeKindInputObjectTypeDefinition:
schema = v.processInputObjectType(node)
case ast.NodeKindScalarTypeDefinition:
schema = NewAnySchema()
// Add description if available
if v.definitionDocument.ScalarTypeDefinitions[node.Ref].Description.IsDefined {
schema.Description = v.definitionDocument.ScalarTypeDefinitionDescriptionString(node.Ref)
}
default:
// If we can't determine the type, default to any
schema = NewAnySchema()
}
// Clean up the recursion tracker before returning
if shouldCleanupTracker {
currentDepth := v.recursionTracker[typeName]
if currentDepth > 1 {
// Decrement the depth as we're exiting the recursion
v.recursionTracker[typeName]--
} else {
// Remove the type from the tracker if depth is 1
delete(v.recursionTracker, typeName)
}
}
return schema
}
// processEnumType processes an enum type definition
func (v *VariablesSchemaBuilder) processEnumType(node ast.Node) *JsonSchema {
values := make([]string, 0)
enumDef := v.definitionDocument.EnumTypeDefinitions[node.Ref]
for _, valueRef := range enumDef.EnumValuesDefinition.Refs {
valueName := v.definitionDocument.EnumValueDefinitionNameString(valueRef)
values = append(values, valueName)
}
schema := NewEnumSchema(values)
// Add description if available
if enumDef.Description.IsDefined {
schema.Description = v.definitionDocument.EnumTypeDefinitionDescriptionString(node.Ref)
}
return schema
}
// processInputObjectType processes an input object type definition
func (v *VariablesSchemaBuilder) processInputObjectType(node ast.Node) *JsonSchema {
schema := NewObjectSchema()
inputDef := v.definitionDocument.InputObjectTypeDefinitions[node.Ref]
// Set description if available
if inputDef.Description.IsDefined {
schema.Description = v.definitionDocument.InputObjectTypeDefinitionDescriptionString(node.Ref)
}
if !inputDef.HasInputFieldsDefinition {
return schema
}
// Process each input field
for _, fieldRef := range inputDef.InputFieldsDefinition.Refs {
v.processInputField(fieldRef, schema)
}
return schema
}
// processInputField processes a single input field
func (v *VariablesSchemaBuilder) processInputField(fieldRef int, schema *JsonSchema) {
fieldName := v.definitionDocument.InputValueDefinitionNameString(fieldRef)
fieldTypeRef := v.definitionDocument.InputValueDefinitionType(fieldRef)
// Process the field type starting from the definition document
fieldSchema := v.processDefinitionTypeRef(fieldTypeRef)
// Skip this field if we reached maximum recursion depth
if fieldSchema == nil {
return
}
// Add to required list if non-nullable
if v.definitionDocument.TypeIsNonNull(fieldTypeRef) {
schema.Required = append(schema.Required, fieldName)
}
// Set field description if exists
if v.definitionDocument.InputValueDefinitions[fieldRef].Description.IsDefined {
description := v.definitionDocument.InputValueDefinitionDescriptionString(fieldRef)
fieldSchema.Description = description
}
// Set default value if exists
if v.definitionDocument.InputValueDefinitionHasDefaultValue(fieldRef) {
defaultValue := v.definitionDocument.InputValueDefinitionDefaultValue(fieldRef)
fieldSchema.Default = v.convertDefinitionValueToNative(defaultValue)
}
// Add field to schema
schema.Properties[fieldName] = fieldSchema
}
// processDefinitionTypeRef processes a type reference from the definition document
func (v *VariablesSchemaBuilder) processDefinitionTypeRef(typeRef int) *JsonSchema {
switch v.definitionDocument.Types[typeRef].TypeKind {
case ast.TypeKindNonNull:
ofType := v.definitionDocument.Types[typeRef].OfType
schema := v.processDefinitionTypeRef(ofType)
if schema == nil {
return nil
}
// Non-null types are not nullable
schema.Nullable = false
return schema
case ast.TypeKindList:
ofType := v.definitionDocument.Types[typeRef].OfType
itemSchema := v.processDefinitionTypeRef(ofType)
if itemSchema == nil {
return nil
}
// If we're not in a non-null context, list is nullable
schema := NewArraySchema(itemSchema)
schema.Nullable = true
return schema
case ast.TypeKindNamed:
typeName := v.definitionDocument.TypeNameString(typeRef)
schema := v.processTypeByName(typeName)
if schema != nil {
// If we're not in a non-null context, named type is nullable
schema.Nullable = true
}
return schema
}
return nil
}
// convertOperationValueToNative converts a GraphQL AST value from the operation document to a native Go value
func (v *VariablesSchemaBuilder) convertOperationValueToNative(value ast.Value) interface{} {
switch value.Kind {
case ast.ValueKindString:
return v.operationDocument.StringValueContentString(value.Ref)
case ast.ValueKindInteger:
return v.operationDocument.IntValueAsInt(value.Ref)
case ast.ValueKindFloat:
return v.operationDocument.FloatValueAsFloat32(value.Ref)
case ast.ValueKindBoolean:
return v.operationDocument.BooleanValue(value.Ref)
case ast.ValueKindNull:
return nil
case ast.ValueKindEnum:
return v.operationDocument.EnumValueNameString(value.Ref)
case ast.ValueKindList:
list := make([]interface{}, 0)
for _, itemRef := range v.operationDocument.ListValues[value.Ref].Refs {
item := v.operationDocument.Value(itemRef)
list = append(list, v.convertOperationValueToNative(item))
}
return list
case ast.ValueKindObject:
obj := make(map[string]interface{})
for _, fieldRef := range v.operationDocument.ObjectValues[value.Ref].Refs {
fieldName := v.operationDocument.ObjectFieldNameString(fieldRef)
fieldValue := v.operationDocument.ObjectFieldValue(fieldRef)
obj[fieldName] = v.convertOperationValueToNative(fieldValue)
}
return obj
}
return nil
}
// convertDefinitionValueToNative converts a GraphQL AST value from the definition document to a native Go value
func (v *VariablesSchemaBuilder) convertDefinitionValueToNative(value ast.Value) interface{} {
switch value.Kind {
case ast.ValueKindString:
return v.definitionDocument.StringValueContentString(value.Ref)
case ast.ValueKindInteger:
return v.definitionDocument.IntValueAsInt(value.Ref)
case ast.ValueKindFloat:
return v.definitionDocument.FloatValueAsFloat32(value.Ref)
case ast.ValueKindBoolean:
return v.definitionDocument.BooleanValue(value.Ref)
case ast.ValueKindNull:
return nil
case ast.ValueKindEnum:
return v.definitionDocument.EnumValueNameString(value.Ref)
case ast.ValueKindList:
list := make([]interface{}, 0)
for _, itemRef := range v.definitionDocument.ListValues[value.Ref].Refs {
item := v.definitionDocument.Value(itemRef)
list = append(list, v.convertDefinitionValueToNative(item))
}
return list
case ast.ValueKindObject:
obj := make(map[string]interface{})
for _, fieldRef := range v.definitionDocument.ObjectValues[value.Ref].Refs {
fieldName := v.definitionDocument.ObjectFieldNameString(fieldRef)
fieldValue := v.definitionDocument.ObjectFieldValue(fieldRef)
obj[fieldName] = v.convertDefinitionValueToNative(fieldValue)
}
return obj
}
return nil
}
// BuildJsonSchema builds a JSON schema for the variables of the given operation
// using the default recursion depth of 1
func BuildJsonSchema(operationDocument, definitionDocument *ast.Document) (*JsonSchema, error) {
return BuildJsonSchemaWithOptions(operationDocument, definitionDocument, 1)
}
// BuildJsonSchemaWithOptions builds a JSON schema for the variables of the given operation
// with a custom recursion depth limit
func BuildJsonSchemaWithOptions(operationDocument, definitionDocument *ast.Document, maxRecursionDepth int) (*JsonSchema, error) {
if len(operationDocument.OperationDefinitions) == 0 {
return nil, fmt.Errorf("no operations found in document")
}
builder := NewVariablesSchemaBuilderWithOptions(operationDocument, definitionDocument, maxRecursionDepth)
return builder.Build()
}