forked from graphql-go/graphql
-
Notifications
You must be signed in to change notification settings - Fork 2
/
rules.go
1901 lines (1770 loc) · 55.8 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"
"reflect"
"sort"
"strings"
"github.com/graphql-go/graphql/gqlerrors"
"github.com/graphql-go/graphql/language/ast"
"github.com/graphql-go/graphql/language/kinds"
"github.com/graphql-go/graphql/language/printer"
"github.com/graphql-go/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,
PossibleFragmentSpreadsRule,
ProvidedNonNullArgumentsRule,
ScalarLeafsRule,
UniqueArgumentNamesRule,
UniqueFragmentNamesRule,
UniqueInputFieldNamesRule,
UniqueOperationNamesRule,
UniqueVariableNamesRule,
VariablesAreInputTypesRule,
VariablesInAllowedPositionRule,
}
type ValidationRuleInstance struct {
VisitorOpts *visitor.VisitorOptions
}
type ValidationRuleFn func(context *ValidationContext) *ValidationRuleInstance
func newValidationError(message string, nodes []ast.Node) *gqlerrors.Error {
return gqlerrors.NewError(
message,
nodes,
"",
nil,
[]int{},
nil, // TODO: this is interim, until we port "better-error-messages-for-inputs"
)
}
func reportError(context *ValidationContext, message string, nodes []ast.Node) (string, interface{}) {
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 {
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.Argument: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
if argAST, ok := p.Node.(*ast.Argument); ok {
if argDef := context.Argument(); argDef != nil {
if isValid, messages := isValidLiteralValue(argDef.Type, argAST.Value); !isValid {
var messagesStr, argNameValue string
if argAST.Name != nil {
argNameValue = argAST.Name.Value
}
if len(messages) > 0 {
messagesStr = "\n" + strings.Join(messages, "\n")
}
reportError(
context,
fmt.Sprintf(`Argument "%v" has invalid value %v.%v`,
argNameValue, printer.Print(argAST.Value), messagesStr),
[]ast.Node{argAST.Value},
)
}
}
}
return visitor.ActionSkip, nil
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
// 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 {
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.VariableDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
if varDefAST, ok := p.Node.(*ast.VariableDefinition); ok {
var (
name string
defaultValue = varDefAST.DefaultValue
messagesStr string
)
if varDefAST.Variable != nil && varDefAST.Variable.Name != nil {
name = varDefAST.Variable.Name.Value
}
ttype := context.InputType()
// when input variable value must be nonNull, and set default value is unnecessary
if ttype, ok := ttype.(*NonNull); ok && defaultValue != nil {
reportError(
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 isValid, messages := isValidLiteralValue(ttype, defaultValue); !isValid && defaultValue != nil {
if len(messages) > 0 {
messagesStr = "\n" + strings.Join(messages, "\n")
}
reportError(
context,
fmt.Sprintf(`Variable "$%v" has invalid default value: %v.%v`,
name, printer.Print(defaultValue), messagesStr),
[]ast.Node{defaultValue},
)
}
}
return visitor.ActionSkip, nil
},
},
kinds.SelectionSet: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
return visitor.ActionSkip, nil
},
},
kinds.FragmentDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
return visitor.ActionSkip, nil
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
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 {
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.Field: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
var action = visitor.ActionNoChange
if node, ok := p.Node.(*ast.Field); ok {
var ttype Composite
if ttype = context.ParentType(); ttype == nil {
return action, nil
}
switch ttype.(type) {
case *Object, *Interface, *Union:
if reflect.ValueOf(ttype).IsNil() {
return action, nil
}
}
fieldDef := context.FieldDef()
if fieldDef == nil {
// This field doesn't exist, lets look for suggestions.
var nodeName string
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?
suggestedFieldNames := []string{}
if len(suggestedTypeNames) == 0 {
suggestedFieldNames = getSuggestedFieldNames(context.Schema(), ttype, nodeName)
}
reportError(
context,
UndefinedFieldMessage(nodeName, ttype.Name(), suggestedTypeNames, suggestedFieldNames),
[]ast.Node{node},
)
}
}
return action, nil
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
// 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 {
var (
suggestedObjectTypes = []string{}
suggestedInterfaces = []*suggestedInterface{}
// stores a map of interface name => index in suggestedInterfaces
suggestedInterfaceMap = map[string]int{}
// stores a maps of object name => true to remove duplicates from results
suggestedObjectMap = map[string]bool{}
)
possibleTypes := schema.PossibleTypes(ttype)
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++
}
}
}
}
// 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 := []string{}
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(schema *Schema, ttype Output, fieldName string) []string {
fields := FieldDefinitionMap{}
switch ttype := ttype.(type) {
case *Object:
fields = ttype.Fields()
case *Interface:
fields = ttype.Fields()
default:
return []string{}
}
possibleFieldNames := []string{}
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 {
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.InlineFragment: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
if node, ok := p.Node.(*ast.InlineFragment); ok {
ttype := context.Type()
if node.TypeCondition != nil && ttype != nil && !IsCompositeType(ttype) {
reportError(
context,
fmt.Sprintf(`Fragment cannot condition on non composite type "%v".`, ttype),
[]ast.Node{node.TypeCondition},
)
}
}
return visitor.ActionNoChange, nil
},
},
kinds.FragmentDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
if node, ok := p.Node.(*ast.FragmentDefinition); ok {
ttype := context.Type()
if ttype != nil && !IsCompositeType(ttype) {
nodeName := ""
if node.Name != nil {
nodeName = node.Name.Value
}
reportError(
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
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
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 {
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.Argument: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
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
}
// verify node, if the node's name exists in Arguments{Field, Directive}
var (
fieldArgDef *Argument
fieldDef = context.FieldDef()
directive = context.Directive()
argNames []string
parentTypeName string
)
switch argumentOf.GetKind() {
case kinds.Field:
// get field definition
if fieldDef == nil {
return action, nil
}
for _, arg := range fieldDef.Args {
if arg.Name() == node.Name.Value {
fieldArgDef = arg
break
}
argNames = append(argNames, arg.Name())
}
if fieldArgDef == nil {
parentType := context.ParentType()
if parentType != nil {
parentTypeName = parentType.Name()
}
reportError(
context,
unknownArgMessage(
node.Name.Value,
fieldDef.Name,
parentTypeName, suggestionList(node.Name.Value, argNames),
),
[]ast.Node{node},
)
}
case kinds.Directive:
if directive = context.Directive(); directive == nil {
return action, nil
}
for _, arg := range directive.Args {
if arg.Name() == node.Name.Value {
fieldArgDef = arg
break
}
argNames = append(argNames, arg.Name())
}
if fieldArgDef == nil {
reportError(
context,
unknownDirectiveArgMessage(
node.Name.Value,
directive.Name,
suggestionList(node.Name.Value, argNames),
),
[]ast.Node{node},
)
}
}
}
return action, nil
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
func MisplaceDirectiveMessage(directiveName string, location string) string {
return fmt.Sprintf(`Directive "%v" may not be used on %v.`, 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 {
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.Directive: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
var action = visitor.ActionNoChange
var result interface{}
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 reportError(
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 == "" {
reportError(
context,
MisplaceDirectiveMessage(nodeName, node.GetKind()),
[]ast.Node{node},
)
} else if !directiveHasLocation {
reportError(
context,
MisplaceDirectiveMessage(nodeName, candidateLocation),
[]ast.Node{node},
)
}
}
return action, result
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
func getDirectiveLocationForASTPath(ancestors []ast.Node) string {
var appliedTo ast.Node
if len(ancestors) > 0 {
appliedTo = ancestors[len(ancestors)-1]
}
if appliedTo == nil {
return ""
}
kind := appliedTo.GetKind()
if kind == kinds.OperationDefinition {
appliedTo, _ := appliedTo.(*ast.OperationDefinition)
if appliedTo.Operation == ast.OperationTypeQuery {
return DirectiveLocationQuery
}
if appliedTo.Operation == ast.OperationTypeMutation {
return DirectiveLocationMutation
}
if appliedTo.Operation == ast.OperationTypeSubscription {
return DirectiveLocationSubscription
}
}
if kind == kinds.Field {
return DirectiveLocationField
}
if kind == kinds.FragmentSpread {
return DirectiveLocationFragmentSpread
}
if kind == kinds.InlineFragment {
return DirectiveLocationInlineFragment
}
if kind == kinds.FragmentDefinition {
return DirectiveLocationFragmentDefinition
}
if kind == kinds.SchemaDefinition {
return DirectiveLocationSchema
}
if kind == kinds.ScalarDefinition {
return DirectiveLocationScalar
}
if kind == kinds.ObjectDefinition {
return DirectiveLocationObject
}
if kind == kinds.FieldDefinition {
return DirectiveLocationFieldDefinition
}
if kind == kinds.InterfaceDefinition {
return DirectiveLocationInterface
}
if kind == kinds.UnionDefinition {
return DirectiveLocationUnion
}
if kind == kinds.EnumDefinition {
return DirectiveLocationEnum
}
if kind == kinds.EnumValueDefinition {
return DirectiveLocationEnumValue
}
if kind == kinds.InputObjectDefinition {
return DirectiveLocationInputObject
}
if kind == kinds.InputValueDefinition {
var parentNode ast.Node
if len(ancestors) >= 3 {
parentNode = ancestors[len(ancestors)-3]
}
if parentNode.GetKind() == kinds.InputObjectDefinition {
return DirectiveLocationInputFieldDefinition
} else {
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 {
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.FragmentSpread: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
var action = visitor.ActionNoChange
var result interface{}
if node, ok := p.Node.(*ast.FragmentSpread); ok {
fragmentName := ""
if node.Name != nil {
fragmentName = node.Name.Value
}
fragment := context.Fragment(fragmentName)
if fragment == nil {
reportError(
context,
fmt.Sprintf(`Unknown fragment "%v".`, fragmentName),
[]ast.Node{node.Name},
)
}
}
return action, result
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
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 {
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.ObjectDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
return visitor.ActionSkip, nil
},
},
kinds.InterfaceDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
return visitor.ActionSkip, nil
},
},
kinds.UnionDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
return visitor.ActionSkip, nil
},
},
kinds.InputObjectDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
return visitor.ActionSkip, nil
},
},
kinds.Named: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
if node, ok := p.Node.(*ast.Named); ok {
typeNameValue := ""
typeName := node.Name
if typeName != nil {
typeNameValue = typeName.Value
}
ttype := context.Schema().Type(typeNameValue)
if ttype == nil {
suggestedTypes := []string{}
for key := range context.Schema().TypeMap() {
suggestedTypes = append(suggestedTypes, key)
}
reportError(
context,
unknownTypeMessage(typeNameValue, suggestionList(typeNameValue, suggestedTypes)),
[]ast.Node{node},
)
}
}
return visitor.ActionNoChange, nil
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
// 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
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.Document: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
if node, ok := p.Node.(*ast.Document); ok {
operationCount = 0
for _, definition := range node.Definitions {
if definition.GetKind() == kinds.OperationDefinition {
operationCount++
}
}
}
return visitor.ActionNoChange, nil
},
},
kinds.OperationDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
if node, ok := p.Node.(*ast.OperationDefinition); ok {
if node.Name == nil && operationCount > 1 {
reportError(
context,
`This anonymous operation must be the only defined operation.`,
[]ast.Node{node},
)
}
}
return visitor.ActionNoChange, nil
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
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 := map[string]bool{}
// Array of AST nodes used to produce meaningful errors
spreadPath := []*ast.FragmentSpread{}
// Position in the spread path
spreadPathIndexByName := 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) {
fragmentName := ""
if fragment.Name != nil {
fragmentName = fragment.Name.Value
}
visitedFrags[fragmentName] = true
spreadNodes := context.FragmentSpreads(fragment.SelectionSet)
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)
reportError(
context,
CycleErrorMessage(spreadName, spreadNames),
nodes,
)
}
}
delete(spreadPathIndexByName, fragmentName)
}
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.OperationDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
return visitor.ActionSkip, nil
},
},
kinds.FragmentDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
if node, ok := p.Node.(*ast.FragmentDefinition); ok && node != nil {
nodeName := ""
if node.Name != nil {
nodeName = node.Name.Value
}
if _, ok := visitedFrags[nodeName]; !ok {
detectCycleRecursive(node)
}
}
return visitor.ActionSkip, nil
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
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{}
visitorOpts := &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.OperationDefinition: {
Enter: func(p visitor.VisitFuncParams) (string, interface{}) {
variableNameDefined = map[string]bool{}
return visitor.ActionNoChange, nil
},
Leave: func(p visitor.VisitFuncParams) (string, interface{}) {
if operation, ok := p.Node.(*ast.OperationDefinition); ok && operation != nil {
usages := context.RecursiveVariableUsages(operation)
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 operation.Name != nil {
opName = operation.Name.Value
}
if res, ok := variableNameDefined[varName]; !ok || !res {
reportError(
context,
UndefinedVarMessage(varName, opName),
[]ast.Node{usage.Node, operation},
)
}
}
}
return visitor.ActionNoChange, nil
},
},
kinds.VariableDefinition: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
if node, ok := p.Node.(*ast.VariableDefinition); ok && node != nil {
variableName := ""
if node.Variable != nil && node.Variable.Name != nil {
variableName = node.Variable.Name.Value
}
variableNameDefined[variableName] = true
}
return visitor.ActionNoChange, nil
},
},
},
}
return &ValidationRuleInstance{
VisitorOpts: visitorOpts,
}
}
// NoUnusedFragmentsRule No unused fragments
//
// A GraphQL document is only valid if all fragment definitions are spread