-
Notifications
You must be signed in to change notification settings - Fork 1
/
rules.go
2052 lines (1906 loc) · 60.9 KB
/
rules.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
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package graphql
import (
"fmt"
"math"
"sort"
"strings"
"github.com/sprucehealth/graphql/gqlerrors"
"github.com/sprucehealth/graphql/language/ast"
"github.com/sprucehealth/graphql/language/printer"
"github.com/sprucehealth/graphql/language/visitor"
)
// SpecifiedRules set includes all validation rules defined by the GraphQL spec.
var SpecifiedRules = []ValidationRuleFn{
ArgumentsOfCorrectTypeRule,
DefaultValuesOfCorrectTypeRule,
FieldsOnCorrectTypeRule,
FragmentsOnCompositeTypesRule,
KnownArgumentNamesRule,
KnownDirectivesRule,
KnownFragmentNamesRule,
KnownTypeNamesRule,
LoneAnonymousOperationRule,
NoFragmentCyclesRule,
NoUndefinedVariablesRule,
NoUnusedFragmentsRule,
NoUnusedVariablesRule,
// OverlappingFieldsCanBeMergedRule, TODO(@samuel): disabled for now as it has a very large performance impact
PossibleFragmentSpreadsRule,
ProvidedNonNullArgumentsRule,
ScalarLeafsRule,
UniqueArgumentNamesRule,
UniqueFragmentNamesRule,
UniqueInputFieldNamesRule,
UniqueOperationNamesRule,
UniqueVariableNamesRule,
VariablesAreInputTypesRule,
VariablesInAllowedPositionRule,
}
type ValidationRuleInstance struct {
Enter visitor.VisitFunc
Leave visitor.VisitFunc
}
type ValidationRuleFn func(context *ValidationContext) *ValidationRuleInstance
func newValidationError(message string, nodes []ast.Node) *gqlerrors.Error {
return gqlerrors.NewError(
gqlerrors.ErrorTypeBadQuery,
message,
nodes,
"",
nil,
[]int{},
nil,
)
}
func reportErrorAndReturn(context *ValidationContext, message string, nodes []ast.Node) (string, any) {
context.ReportError(newValidationError(message, nodes))
return visitor.ActionNoChange, nil
}
// ArgumentsOfCorrectTypeRule Argument values of correct type
//
// A GraphQL document is only valid if all field argument literal values are
// of the type expected by their position.
func ArgumentsOfCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance {
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
if argAST, ok := p.Node.(*ast.Argument); ok {
value := argAST.Value
argDef := context.Argument()
if argDef != nil {
isValid, messages := isValidLiteralValue(argDef.Type, value)
if !isValid {
argNameValue := ""
if argAST.Name != nil {
argNameValue = argAST.Name.Value
}
var messagesStr string
if len(messages) > 0 {
messagesStr = "\n" + strings.Join(messages, "\n")
}
return reportErrorAndReturn(
context,
fmt.Sprintf(`Argument "%v" has invalid value %v.%v`,
argNameValue, printer.Print(value), messagesStr),
[]ast.Node{value},
)
}
}
return visitor.ActionSkip, nil
}
return visitor.ActionNoChange, nil
},
}
}
// DefaultValuesOfCorrectTypeRule Variable default values of correct type
//
// A GraphQL document is only valid if all variable default values are of the
// type expected by their definition.
func DefaultValuesOfCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance {
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
switch node := p.Node.(type) {
case *ast.VariableDefinition:
name := ""
if node.Variable != nil && node.Variable.Name != nil {
name = node.Variable.Name.Value
}
defaultValue := node.DefaultValue
ttype := context.InputType()
if ttype, ok := ttype.(*NonNull); ok && defaultValue != nil {
return reportErrorAndReturn(
context,
fmt.Sprintf(`Variable "$%v" of type "%v" is required and will not use the default value. Perhaps you meant to use type "%v".`,
name, ttype, ttype.OfType),
[]ast.Node{defaultValue},
)
}
if ttype != nil && defaultValue != nil {
isValid, messages := isValidLiteralValue(ttype, defaultValue)
if ttype != nil && defaultValue != nil && !isValid {
var messagesStr string
if len(messages) > 0 {
messagesStr = "\n" + strings.Join(messages, "\n")
}
return reportErrorAndReturn(
context,
fmt.Sprintf(`Variable "$%v" has invalid default value: %v.%v`,
name, printer.Print(defaultValue), messagesStr),
[]ast.Node{defaultValue},
)
}
}
return visitor.ActionSkip, nil
case *ast.SelectionSet:
return visitor.ActionSkip, nil
case *ast.FragmentDefinition:
return visitor.ActionSkip, nil
}
return visitor.ActionNoChange, nil
},
}
}
func quoteStrings(slice []string) []string {
quoted := []string{}
for _, s := range slice {
quoted = append(quoted, fmt.Sprintf(`"%v"`, s))
}
return quoted
}
// quotedOrList Given [ A, B, C ] return '"A", "B", or "C"'.
// Notice oxford comma
func quotedOrList(slice []string) string {
maxLength := 5
if len(slice) == 0 {
return ""
}
quoted := quoteStrings(slice)
if maxLength > len(quoted) {
maxLength = len(quoted)
}
if maxLength > 2 {
return fmt.Sprintf("%v, or %v", strings.Join(quoted[0:maxLength-1], ", "), quoted[maxLength-1])
}
if maxLength > 1 {
return fmt.Sprintf("%v or %v", strings.Join(quoted[0:maxLength-1], ", "), quoted[maxLength-1])
}
return quoted[0]
}
func UndefinedFieldMessage(fieldName string, ttypeName string, suggestedTypeNames []string, suggestedFieldNames []string) string {
message := fmt.Sprintf(`Cannot query field "%v" on type "%v".`, fieldName, ttypeName)
if len(suggestedTypeNames) > 0 {
message = fmt.Sprintf(`%v Did you mean to use an inline fragment on %v?`, message, quotedOrList(suggestedTypeNames))
} else if len(suggestedFieldNames) > 0 {
message = fmt.Sprintf(`%v Did you mean %v?`, message, quotedOrList(suggestedFieldNames))
}
return message
}
// FieldsOnCorrectTypeRule Fields on correct type
//
// A GraphQL document is only valid if all fields selected are defined by the
// parent type, or are an allowed meta field such as __typenamme
func FieldsOnCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance {
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
var action = visitor.ActionNoChange
if node, ok := p.Node.(*ast.Field); ok {
ttype := context.ParentType()
if ttype != nil {
fieldDef := context.FieldDef()
// This isn't valid. Let's find suggestions, if any.
if fieldDef == nil {
nodeName := ""
if node.Name != nil {
nodeName = node.Name.Value
}
// First determine if there are any suggested types to condition on.
suggestedTypeNames := getSuggestedTypeNames(context.Schema(), ttype, nodeName)
// If there are no suggested types, then perhaps this was a typo?
var suggestedFieldNames []string
if len(suggestedTypeNames) == 0 {
suggestedFieldNames = getSuggestedFieldNames(ttype, nodeName)
}
context.ReportError(newValidationError(
UndefinedFieldMessage(nodeName, ttype.Name(), suggestedTypeNames, suggestedFieldNames),
[]ast.Node{node}))
}
}
}
return action, nil
},
}
}
// getSuggestedTypeNames Go through all of the implementations of type, as well as the interfaces
// that they implement. If any of those types include the provided field,
// suggest them, sorted by how often the type is referenced, starting
// with Interfaces.
func getSuggestedTypeNames(schema *Schema, ttype Output, fieldName string) []string {
possibleTypes := schema.PossibleTypes(ttype)
var suggestedObjectTypes []string
var suggestedInterfaces []*suggestedInterface
// stores a map of interface name => index in suggestedInterfaces
suggestedInterfaceMap := make(map[string]int)
// stores a maps of object name => true to remove duplicates from results
suggestedObjectMap := make(map[string]bool)
for _, possibleType := range possibleTypes {
if field, ok := possibleType.Fields()[fieldName]; !ok || field == nil {
continue
}
// This object type defines this field.
suggestedObjectTypes = append(suggestedObjectTypes, possibleType.Name())
suggestedObjectMap[possibleType.Name()] = true
for _, possibleInterface := range possibleType.Interfaces() {
if field, ok := possibleInterface.Fields()[fieldName]; !ok || field == nil {
continue
}
// This interface type defines this field.
// - find the index of the suggestedInterface and retrieving the interface
// - increase count
index, ok := suggestedInterfaceMap[possibleInterface.Name()]
if !ok {
suggestedInterfaces = append(suggestedInterfaces, &suggestedInterface{
name: possibleInterface.Name(),
count: 0,
})
index = len(suggestedInterfaces) - 1
suggestedInterfaceMap[possibleInterface.Name()] = index
}
if index < len(suggestedInterfaces) {
s := suggestedInterfaces[index]
if s.name == possibleInterface.Name() {
s.count = s.count + 1
}
}
}
}
// sort results (by count usage for interfaces, alphabetical order for objects)
sort.Sort(suggestedInterfaceSortedSlice(suggestedInterfaces))
sort.Sort(sort.StringSlice(suggestedObjectTypes))
// return concatenated slices of both interface and object type names
// and removing duplicates
// ordered by: interface (sorted) and object (sorted)
results := make([]string, 0, len(suggestedInterfaces))
for _, s := range suggestedInterfaces {
if _, ok := suggestedObjectMap[s.name]; !ok {
results = append(results, s.name)
}
}
results = append(results, suggestedObjectTypes...)
return results
}
// getSuggestedFieldNames For the field name provided, determine if there are any similar field names
// that may be the result of a typo.
func getSuggestedFieldNames(ttype Output, fieldName string) []string {
var fields FieldDefinitionMap
switch ttype := ttype.(type) {
case *Object:
fields = ttype.Fields()
case *Interface:
fields = ttype.Fields()
default:
return []string{}
}
possibleFieldNames := make([]string, 0, len(fields))
for possibleFieldName := range fields {
possibleFieldNames = append(possibleFieldNames, possibleFieldName)
}
return suggestionList(fieldName, possibleFieldNames)
}
// suggestedInterface an internal struct to sort interface by usage count
type suggestedInterface struct {
name string
count int
}
type suggestedInterfaceSortedSlice []*suggestedInterface
func (s suggestedInterfaceSortedSlice) Len() int {
return len(s)
}
func (s suggestedInterfaceSortedSlice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s suggestedInterfaceSortedSlice) Less(i, j int) bool {
if s[i].count == s[j].count {
return s[i].name < s[j].name
}
return s[i].count > s[j].count
}
// FragmentsOnCompositeTypesRule Fragments on composite type
//
// Fragments use a type condition to determine if they apply, since fragments
// can only be spread into a composite type (object, interface, or union), the
// type condition must also be a composite type.
func FragmentsOnCompositeTypesRule(context *ValidationContext) *ValidationRuleInstance {
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
switch node := p.Node.(type) {
case *ast.InlineFragment:
ttype := context.Type()
if node.TypeCondition != nil && ttype != nil && !IsCompositeType(ttype) {
return reportErrorAndReturn(
context,
fmt.Sprintf(`Fragment cannot condition on non composite type "%v".`, ttype),
[]ast.Node{node.TypeCondition},
)
}
case *ast.FragmentDefinition:
ttype := context.Type()
if ttype != nil && !IsCompositeType(ttype) {
nodeName := ""
if node.Name != nil {
nodeName = node.Name.Value
}
return reportErrorAndReturn(
context,
fmt.Sprintf(`Fragment "%v" cannot condition on non composite type "%v".`, nodeName, printer.Print(node.TypeCondition)),
[]ast.Node{node.TypeCondition},
)
}
}
return visitor.ActionNoChange, nil
},
}
}
func unknownArgMessage(argName string, fieldName string, parentTypeName string, suggestedArgs []string) string {
message := fmt.Sprintf(`Unknown argument "%v" on field "%v" of type "%v".`, argName, fieldName, parentTypeName)
if len(suggestedArgs) > 0 {
message = fmt.Sprintf(`%v Did you mean %v?`, message, quotedOrList(suggestedArgs))
}
return message
}
func unknownDirectiveArgMessage(argName string, directiveName string, suggestedArgs []string) string {
message := fmt.Sprintf(`Unknown argument "%v" on directive "@%v".`, argName, directiveName)
if len(suggestedArgs) > 0 {
message = fmt.Sprintf(`%v Did you mean %v?`, message, quotedOrList(suggestedArgs))
}
return message
}
// KnownArgumentNamesRule Known argument names
//
// A GraphQL field is only valid if all supplied arguments are defined by
// that field.
func KnownArgumentNamesRule(context *ValidationContext) *ValidationRuleInstance {
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
var action = visitor.ActionNoChange
if node, ok := p.Node.(*ast.Argument); ok {
var argumentOf ast.Node
if len(p.Ancestors) > 0 {
argumentOf = p.Ancestors[len(p.Ancestors)-1]
}
if argumentOf == nil {
return action, nil
}
switch argumentOf.(type) {
case *ast.Field:
fieldDef := context.FieldDef()
if fieldDef == nil {
return action, nil
}
nodeName := ""
if node.Name != nil {
nodeName = node.Name.Value
}
argNames := make([]string, 0, len(fieldDef.Args))
var fieldArgDef *Argument
for _, arg := range fieldDef.Args {
argNames = append(argNames, arg.Name())
if arg.Name() == nodeName {
fieldArgDef = arg
}
}
if fieldArgDef == nil {
parentType := context.ParentType()
parentTypeName := ""
if parentType != nil {
parentTypeName = parentType.Name()
}
return reportErrorAndReturn(
context,
unknownArgMessage(nodeName, fieldDef.Name, parentTypeName, suggestionList(nodeName, argNames)),
[]ast.Node{node},
)
}
case *ast.Directive:
directive := context.Directive()
if directive == nil {
return action, nil
}
nodeName := ""
if node.Name != nil {
nodeName = node.Name.Value
}
argNames := make([]string, 0, len(directive.Args))
var directiveArgDef *Argument
for _, arg := range directive.Args {
argNames = append(argNames, arg.Name())
if arg.Name() == nodeName {
directiveArgDef = arg
}
}
if directiveArgDef == nil {
return reportErrorAndReturn(
context,
unknownDirectiveArgMessage(nodeName, directive.Name, suggestionList(nodeName, argNames)),
[]ast.Node{node},
)
}
}
}
return action, nil
},
}
}
func MisplaceDirectiveMessage(directiveName, location string) string {
return fmt.Sprintf(`Directive "%s" may not be used on %s.`, directiveName, location)
}
// KnownDirectivesRule Known directives
//
// A GraphQL document is only valid if all `@directives` are known by the
// schema and legally positioned.
func KnownDirectivesRule(context *ValidationContext) *ValidationRuleInstance {
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
if node, ok := p.Node.(*ast.Directive); ok {
nodeName := ""
if node.Name != nil {
nodeName = node.Name.Value
}
var directiveDef *Directive
for _, def := range context.Schema().Directives() {
if def.Name == nodeName {
directiveDef = def
}
}
if directiveDef == nil {
return reportErrorAndReturn(
context,
fmt.Sprintf(`Unknown directive "%v".`, nodeName),
[]ast.Node{node},
)
}
candidateLocation := getDirectiveLocationForASTPath(p.Ancestors)
directiveHasLocation := false
for _, loc := range directiveDef.Locations {
if loc == candidateLocation {
directiveHasLocation = true
break
}
}
if candidateLocation == "" {
context.ReportError(newValidationError(
MisplaceDirectiveMessage(nodeName, fmt.Sprintf("%T", node)),
[]ast.Node{node}))
} else if !directiveHasLocation {
context.ReportError(newValidationError(
MisplaceDirectiveMessage(nodeName, candidateLocation),
[]ast.Node{node}))
}
}
return visitor.ActionNoChange, nil
},
}
}
func getDirectiveLocationForASTPath(ancestors []ast.Node) string {
var appliedTo ast.Node
if len(ancestors) > 0 {
appliedTo = ancestors[len(ancestors)-1]
}
if appliedTo == nil {
return ""
}
switch appliedTo := appliedTo.(type) {
case *ast.OperationDefinition:
if appliedTo.Operation == ast.OperationTypeQuery {
return DirectiveLocationQuery
}
if appliedTo.Operation == ast.OperationTypeMutation {
return DirectiveLocationMutation
}
if appliedTo.Operation == ast.OperationTypeSubscription {
return DirectiveLocationSubscription
}
case *ast.Field:
return DirectiveLocationField
case *ast.FragmentSpread:
return DirectiveLocationFragmentSpread
case *ast.InlineFragment:
return DirectiveLocationInlineFragment
case *ast.FragmentDefinition:
return DirectiveLocationFragmentDefinition
case *ast.SchemaDefinition:
return DirectiveLocationSchema
case *ast.ScalarDefinition:
return DirectiveLocationScalar
case *ast.ObjectDefinition:
return DirectiveLocationObject
case *ast.FieldDefinition:
return DirectiveLocationFieldDefinition
case *ast.InterfaceDefinition:
return DirectiveLocationInterface
case *ast.UnionDefinition:
return DirectiveLocationUnion
case *ast.EnumDefinition:
return DirectiveLocationEnum
case *ast.EnumValueDefinition:
return DirectiveLocationEnumValue
case *ast.InputObjectDefinition:
return DirectiveLocationInputObject
case *ast.InputValueDefinition:
var parentNode ast.Node
if len(ancestors) >= 2 {
parentNode = ancestors[len(ancestors)-2]
}
if _, ok := parentNode.(*ast.InputObjectDefinition); ok {
return DirectiveLocationInputFieldDefinition
}
return DirectiveLocationArgumentDefinition
}
return ""
}
// KnownFragmentNamesRule Known fragment names
//
// A GraphQL document is only valid if all `...Fragment` fragment spreads refer
// to fragments defined in the same document.
func KnownFragmentNamesRule(context *ValidationContext) *ValidationRuleInstance {
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
var action = visitor.ActionNoChange
if node, ok := p.Node.(*ast.FragmentSpread); ok {
fragmentName := ""
if node.Name != nil {
fragmentName = node.Name.Value
}
fragment := context.Fragment(fragmentName)
if fragment == nil {
return reportErrorAndReturn(
context,
fmt.Sprintf(`Unknown fragment "%v".`, fragmentName),
[]ast.Node{node.Name},
)
}
}
return action, nil
},
}
}
func unknownTypeMessage(typeName string, suggestedTypes []string) string {
message := fmt.Sprintf(`Unknown type "%v".`, typeName)
if len(suggestedTypes) > 0 {
message = fmt.Sprintf(`%v Did you mean %v?`, message, quotedOrList(suggestedTypes))
}
return message
}
// KnownTypeNamesRule Known type names
//
// A GraphQL document is only valid if referenced types (specifically
// variable definitions and fragment conditions) are defined by the type schema.
func KnownTypeNamesRule(context *ValidationContext) *ValidationRuleInstance {
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
switch node := p.Node.(type) {
case *ast.ObjectDefinition:
return visitor.ActionSkip, nil
case *ast.InterfaceDefinition:
return visitor.ActionSkip, nil
case *ast.UnionDefinition:
return visitor.ActionSkip, nil
case *ast.InputObjectDefinition:
return visitor.ActionSkip, nil
case *ast.Named:
typeNameValue := ""
typeName := node.Name
if typeName != nil {
typeNameValue = typeName.Value
}
ttype := context.Schema().Type(typeNameValue)
if ttype == nil {
typeMap := context.Schema().TypeMap()
suggestedTypes := make([]string, 0, len(typeMap))
for key := range typeMap {
suggestedTypes = append(suggestedTypes, key)
}
return reportErrorAndReturn(
context,
unknownTypeMessage(typeNameValue, suggestionList(typeNameValue, suggestedTypes)),
[]ast.Node{node},
)
}
}
return visitor.ActionNoChange, nil
},
}
}
// LoneAnonymousOperationRule Lone anonymous operation
//
// A GraphQL document is only valid if when it contains an anonymous operation
// (the query short-hand) that it contains only that one operation definition.
func LoneAnonymousOperationRule(context *ValidationContext) *ValidationRuleInstance {
var operationCount = 0
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
switch node := p.Node.(type) {
case *ast.Document:
operationCount = 0
for _, definition := range node.Definitions {
if _, ok := definition.(*ast.OperationDefinition); ok {
operationCount = operationCount + 1
}
}
case *ast.OperationDefinition:
if node.Name == nil && operationCount > 1 {
return reportErrorAndReturn(
context,
`This anonymous operation must be the only defined operation.`,
[]ast.Node{node},
)
}
}
return visitor.ActionNoChange, nil
},
}
}
func CycleErrorMessage(fragName string, spreadNames []string) string {
via := ""
if len(spreadNames) > 0 {
via = " via " + strings.Join(spreadNames, ", ")
}
return fmt.Sprintf(`Cannot spread fragment "%v" within itself%v.`, fragName, via)
}
// NoFragmentCyclesRule No fragment cycles
func NoFragmentCyclesRule(context *ValidationContext) *ValidationRuleInstance {
// Tracks already visited fragments to maintain O(N) and to ensure that cycles
// are not redundantly reported.
visitedFrags := make(map[string]bool)
// Array of AST nodes used to produce meaningful errors
var spreadPath []*ast.FragmentSpread
// Position in the spread path
spreadPathIndexByName := make(map[string]int)
// This does a straight-forward DFS to find cycles.
// It does not terminate when a cycle was found but continues to explore
// the graph to find all possible cycles.
var detectCycleRecursive func(fragment *ast.FragmentDefinition)
detectCycleRecursive = func(fragment *ast.FragmentDefinition) {
var fragmentName string
if fragment.Name != nil {
fragmentName = fragment.Name.Value
}
visitedFrags[fragmentName] = true
spreadNodes := context.FragmentSpreads(fragment)
if len(spreadNodes) == 0 {
return
}
spreadPathIndexByName[fragmentName] = len(spreadPath)
for _, spreadNode := range spreadNodes {
spreadName := ""
if spreadNode.Name != nil {
spreadName = spreadNode.Name.Value
}
cycleIndex, ok := spreadPathIndexByName[spreadName]
if !ok {
spreadPath = append(spreadPath, spreadNode)
if visited, ok := visitedFrags[spreadName]; !ok || !visited {
spreadFragment := context.Fragment(spreadName)
if spreadFragment != nil {
detectCycleRecursive(spreadFragment)
}
}
spreadPath = spreadPath[:len(spreadPath)-1]
} else {
cyclePath := spreadPath[cycleIndex:]
spreadNames := []string{}
for _, s := range cyclePath {
name := ""
if s.Name != nil {
name = s.Name.Value
}
spreadNames = append(spreadNames, name)
}
nodes := []ast.Node{}
for _, c := range cyclePath {
nodes = append(nodes, c)
}
nodes = append(nodes, spreadNode)
context.ReportError(newValidationError(
CycleErrorMessage(spreadName, spreadNames),
nodes))
}
}
delete(spreadPathIndexByName, fragmentName)
}
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
switch node := p.Node.(type) {
case *ast.OperationDefinition:
return visitor.ActionSkip, nil
case *ast.FragmentDefinition:
nodeName := ""
if node.Name != nil {
nodeName = node.Name.Value
}
if _, ok := visitedFrags[nodeName]; !ok {
detectCycleRecursive(node)
}
return visitor.ActionSkip, nil
}
return visitor.ActionNoChange, nil
},
}
}
func UndefinedVarMessage(varName string, opName string) string {
if opName != "" {
return fmt.Sprintf(`Variable "$%v" is not defined by operation "%v".`, varName, opName)
}
return fmt.Sprintf(`Variable "$%v" is not defined.`, varName)
}
// NoUndefinedVariablesRule No undefined variables
//
// A GraphQL operation is only valid if all variables encountered, both directly
// and via fragment spreads, are defined by that operation.
func NoUndefinedVariablesRule(context *ValidationContext) *ValidationRuleInstance {
var variableNameDefined = map[string]bool{}
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
switch node := p.Node.(type) {
case *ast.OperationDefinition:
variableNameDefined = map[string]bool{}
case *ast.VariableDefinition:
variableName := ""
if node.Variable != nil && node.Variable.Name != nil {
variableName = node.Variable.Name.Value
}
variableNameDefined[variableName] = true
}
return visitor.ActionNoChange, nil
},
Leave: func(p visitor.VisitFuncParams) (string, any) {
switch node := p.Node.(type) {
case *ast.OperationDefinition:
usages := context.RecursiveVariableUsages(node)
for _, usage := range usages {
if usage == nil {
continue
}
if usage.Node == nil {
continue
}
varName := ""
if usage.Node.Name != nil {
varName = usage.Node.Name.Value
}
opName := ""
if node.Name != nil {
opName = node.Name.Value
}
if res, ok := variableNameDefined[varName]; !ok || !res {
context.ReportError(newValidationError(
UndefinedVarMessage(varName, opName),
[]ast.Node{usage.Node, node}))
}
}
}
return visitor.ActionNoChange, nil
},
}
}
// NoUnusedFragmentsRule No unused fragments
//
// A GraphQL document is only valid if all fragment definitions are spread
// within operations, or spread within other fragments spread within operations.
func NoUnusedFragmentsRule(context *ValidationContext) *ValidationRuleInstance {
var fragmentDefs []*ast.FragmentDefinition
var operationDefs []*ast.OperationDefinition
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
switch node := p.Node.(type) {
case *ast.OperationDefinition:
operationDefs = append(operationDefs, node)
return visitor.ActionSkip, nil
case *ast.FragmentDefinition:
fragmentDefs = append(fragmentDefs, node)
return visitor.ActionSkip, nil
}
return visitor.ActionNoChange, nil
},
Leave: func(p visitor.VisitFuncParams) (string, any) {
switch p.Node.(type) {
case *ast.Document:
fragmentNameUsed := make(map[string]bool)
for _, operation := range operationDefs {
fragments := context.RecursivelyReferencedFragments(operation)
for _, fragment := range fragments {
var fragName string
if fragment.Name != nil {
fragName = fragment.Name.Value
}
fragmentNameUsed[fragName] = true
}
}
for _, def := range fragmentDefs {
defName := ""
if def.Name != nil {
defName = def.Name.Value
}
isFragNameUsed, ok := fragmentNameUsed[defName]
if !ok || !isFragNameUsed {
context.ReportError(newValidationError(
fmt.Sprintf(`Fragment "%v" is never used.`, defName),
[]ast.Node{def}))
}
}
}
return visitor.ActionNoChange, nil
},
}
}
func UnusedVariableMessage(varName string, opName string) string {
if opName != "" {
return fmt.Sprintf(`Variable "$%v" is never used in operation "%v".`, varName, opName)
}
return fmt.Sprintf(`Variable "$%v" is never used.`, varName)
}
// NoUnusedVariablesRule No unused variables
//
// A GraphQL operation is only valid if all variables defined by an operation
// are used, either directly or within a spread fragment.
func NoUnusedVariablesRule(context *ValidationContext) *ValidationRuleInstance {
var variableDefs = []*ast.VariableDefinition{}
return &ValidationRuleInstance{
Enter: func(p visitor.VisitFuncParams) (string, any) {
switch def := p.Node.(type) {
case *ast.OperationDefinition:
variableDefs = variableDefs[:0]
case *ast.VariableDefinition:
variableDefs = append(variableDefs, def)
}
return visitor.ActionNoChange, nil
},
Leave: func(p visitor.VisitFuncParams) (string, any) {
if operation, ok := p.Node.(*ast.OperationDefinition); ok {
usages := context.RecursiveVariableUsages(operation)
variableNameUsed := make(map[string]bool, len(usages))
for _, usage := range usages {
var varName string
if usage != nil && usage.Node != nil && usage.Node.Name != nil {
varName = usage.Node.Name.Value
}
if varName != "" {
variableNameUsed[varName] = true
}
}
for _, variableDef := range variableDefs {
var variableName string
if variableDef != nil && variableDef.Variable != nil && variableDef.Variable.Name != nil {
variableName = variableDef.Variable.Name.Value
}
var opName string
if operation.Name != nil {
opName = operation.Name.Value
}
if res, ok := variableNameUsed[variableName]; !ok || !res {
context.ReportError(newValidationError(
UnusedVariableMessage(variableName, opName),
[]ast.Node{variableDef}))
}
}
}
return visitor.ActionNoChange, nil
},
}
}
type fieldDefPair struct {
ParentType Composite
Field *ast.Field
FieldDef *FieldDefinition
}
func collectFieldASTsAndDefs(context *ValidationContext, parentType Named, selectionSet *ast.SelectionSet, visitedFragmentNames map[string]struct{}, astAndDefs map[string][]*fieldDefPair) map[string][]*fieldDefPair {
if astAndDefs == nil {
astAndDefs = make(map[string][]*fieldDefPair)
}
if visitedFragmentNames == nil {
visitedFragmentNames = make(map[string]struct{})
}
if selectionSet == nil {
return astAndDefs
}
for _, selection := range selectionSet.Selections {
switch selection := selection.(type) {
case *ast.Field:
fieldName := ""
if selection.Name != nil {
fieldName = selection.Name.Value
}
var fieldDef *FieldDefinition
if parentType, ok := parentType.(*Object); ok {
fieldDef = parentType.Fields()[fieldName]
}
if parentType, ok := parentType.(*Interface); ok {
fieldDef = parentType.Fields()[fieldName]
}
responseName := fieldName
if selection.Alias != nil {
responseName = selection.Alias.Value
}
// astAndDefs[responseName] = append(astAndDefs[responseName], &fieldDefPair{
// Field: selection,
// FieldDef: fieldDef,
// })
_, ok := astAndDefs[responseName]
if !ok {
astAndDefs[responseName] = []*fieldDefPair{}