forked from graphql-go/graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.go
1079 lines (961 loc) · 31.8 KB
/
executor.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 (
"context"
"errors"
"fmt"
"reflect"
"sort"
"strings"
"github.com/graphql-go/graphql/gqlerrors"
"github.com/graphql-go/graphql/language/ast"
)
type ExecuteParams struct {
Schema Schema
Root interface{}
AST *ast.Document
OperationName string
Args map[string]interface{}
// Context may be provided to pass application-specific per-request
// information to resolve functions.
Context context.Context
}
func Execute(p ExecuteParams) (result *Result) {
// Use background context if no context was provided
ctx := p.Context
if ctx == nil {
ctx = context.Background()
}
// run executionDidStart functions from extensions
extErrs, executionFinishFn := handleExtensionsExecutionDidStart(&p)
if len(extErrs) != 0 {
return &Result{
Errors: extErrs,
}
}
defer func() {
extErrs = executionFinishFn(result)
if len(extErrs) != 0 {
result.Errors = append(result.Errors, extErrs...)
}
addExtensionResults(&p, result)
}()
resultChannel := make(chan *Result, 2)
go func() {
result := &Result{}
defer func() {
if err := recover(); err != nil {
result.Errors = append(result.Errors, gqlerrors.FormatError(err.(error)))
}
resultChannel <- result
}()
exeContext, err := buildExecutionContext(buildExecutionCtxParams{
Schema: p.Schema,
Root: p.Root,
AST: p.AST,
OperationName: p.OperationName,
Args: p.Args,
Result: result,
Context: p.Context,
})
if err != nil {
result.Errors = append(result.Errors, gqlerrors.FormatError(err.(error)))
resultChannel <- result
return
}
resultChannel <- executeOperation(executeOperationParams{
ExecutionContext: exeContext,
Root: p.Root,
Operation: exeContext.Operation,
})
}()
select {
case <-ctx.Done():
result := &Result{}
result.Errors = append(result.Errors, gqlerrors.FormatError(ctx.Err()))
return result
case r := <-resultChannel:
return r
}
}
type buildExecutionCtxParams struct {
Schema Schema
Root interface{}
AST *ast.Document
OperationName string
Args map[string]interface{}
Result *Result
Context context.Context
}
type executionContext struct {
Schema Schema
Fragments map[string]ast.Definition
Root interface{}
Operation ast.Definition
VariableValues map[string]interface{}
Errors []gqlerrors.FormattedError
Context context.Context
}
func buildExecutionContext(p buildExecutionCtxParams) (*executionContext, error) {
eCtx := &executionContext{}
var operation *ast.OperationDefinition
fragments := map[string]ast.Definition{}
for _, definition := range p.AST.Definitions {
switch definition := definition.(type) {
case *ast.OperationDefinition:
if (p.OperationName == "") && operation != nil {
return nil, errors.New("Must provide operation name if query contains multiple operations.")
}
if p.OperationName == "" || definition.GetName() != nil && definition.GetName().Value == p.OperationName {
operation = definition
}
case *ast.FragmentDefinition:
key := ""
if definition.GetName() != nil && definition.GetName().Value != "" {
key = definition.GetName().Value
}
fragments[key] = definition
default:
return nil, fmt.Errorf("GraphQL cannot execute a request containing a %v", definition.GetKind())
}
}
if operation == nil {
if p.OperationName != "" {
return nil, fmt.Errorf(`Unknown operation named "%v".`, p.OperationName)
}
return nil, fmt.Errorf(`Must provide an operation.`)
}
variableValues, err := getVariableValues(p.Schema, operation.GetVariableDefinitions(), p.Args)
if err != nil {
return nil, err
}
eCtx.Schema = p.Schema
eCtx.Fragments = fragments
eCtx.Root = p.Root
eCtx.Operation = operation
eCtx.VariableValues = variableValues
eCtx.Context = p.Context
return eCtx, nil
}
type executeOperationParams struct {
ExecutionContext *executionContext
Root interface{}
Operation ast.Definition
}
func executeOperation(p executeOperationParams) *Result {
operationType, err := getOperationRootType(p.ExecutionContext.Schema, p.Operation)
if err != nil {
return &Result{Errors: gqlerrors.FormatErrors(err)}
}
fields := collectFields(collectFieldsParams{
ExeContext: p.ExecutionContext,
RuntimeType: operationType,
SelectionSet: p.Operation.GetSelectionSet(),
})
executeFieldsParams := executeFieldsParams{
ExecutionContext: p.ExecutionContext,
ParentType: operationType,
Source: p.Root,
Fields: fields,
}
if p.Operation.GetOperation() == ast.OperationTypeMutation {
return executeFieldsSerially(executeFieldsParams)
}
return executeFields(executeFieldsParams)
}
// Extracts the root type of the operation from the schema.
func getOperationRootType(schema Schema, operation ast.Definition) (*Object, error) {
if operation == nil {
return nil, errors.New("Can only execute queries, mutations and subscription")
}
switch operation.GetOperation() {
case ast.OperationTypeQuery:
return schema.QueryType(), nil
case ast.OperationTypeMutation:
mutationType := schema.MutationType()
if mutationType == nil || mutationType.PrivateName == "" {
return nil, gqlerrors.NewError(
"Schema is not configured for mutations",
[]ast.Node{operation},
"",
nil,
[]int{},
nil,
)
}
return mutationType, nil
case ast.OperationTypeSubscription:
subscriptionType := schema.SubscriptionType()
if subscriptionType == nil || subscriptionType.PrivateName == "" {
return nil, gqlerrors.NewError(
"Schema is not configured for subscriptions",
[]ast.Node{operation},
"",
nil,
[]int{},
nil,
)
}
return subscriptionType, nil
default:
return nil, gqlerrors.NewError(
"Can only execute queries, mutations and subscription",
[]ast.Node{operation},
"",
nil,
[]int{},
nil,
)
}
}
type executeFieldsParams struct {
ExecutionContext *executionContext
ParentType *Object
Source interface{}
Fields map[string][]*ast.Field
Path *ResponsePath
}
// Implements the "Evaluating selection sets" section of the spec for "write" mode.
func executeFieldsSerially(p executeFieldsParams) *Result {
if p.Source == nil {
p.Source = map[string]interface{}{}
}
if p.Fields == nil {
p.Fields = map[string][]*ast.Field{}
}
finalResults := make(map[string]interface{}, len(p.Fields))
for _, orderedField := range orderedFields(p.Fields) {
responseName := orderedField.responseName
fieldASTs := orderedField.fieldASTs
fieldPath := p.Path.WithKey(responseName)
resolved, state := resolveField(p.ExecutionContext, p.ParentType, p.Source, fieldASTs, fieldPath)
if state.hasNoFieldDefs {
continue
}
finalResults[responseName] = resolved
}
dethunkMapDepthFirst(finalResults)
return &Result{
Data: finalResults,
Errors: p.ExecutionContext.Errors,
}
}
// Implements the "Evaluating selection sets" section of the spec for "read" mode.
func executeFields(p executeFieldsParams) *Result {
finalResults := executeSubFields(p)
dethunkMapWithBreadthFirstTraversal(finalResults)
return &Result{
Data: finalResults,
Errors: p.ExecutionContext.Errors,
}
}
func executeSubFields(p executeFieldsParams) map[string]interface{} {
if p.Source == nil {
p.Source = map[string]interface{}{}
}
if p.Fields == nil {
p.Fields = map[string][]*ast.Field{}
}
finalResults := make(map[string]interface{}, len(p.Fields))
for responseName, fieldASTs := range p.Fields {
fieldPath := p.Path.WithKey(responseName)
resolved, state := resolveField(p.ExecutionContext, p.ParentType, p.Source, fieldASTs, fieldPath)
if state.hasNoFieldDefs {
continue
}
finalResults[responseName] = resolved
}
return finalResults
}
// dethunkQueue is a structure that allows us to execute a classic breadth-first traversal.
type dethunkQueue struct {
DethunkFuncs []func()
}
func (d *dethunkQueue) push(f func()) {
d.DethunkFuncs = append(d.DethunkFuncs, f)
}
func (d *dethunkQueue) shift() func() {
f := d.DethunkFuncs[0]
d.DethunkFuncs = d.DethunkFuncs[1:]
return f
}
// dethunkWithBreadthFirstTraversal performs a breadth-first descent of the map, calling any thunks
// in the map values and replacing each thunk with that thunk's return value. This parallels
// the reference graphql-js implementation, which calls Promise.all on thunks at each depth (which
// is an implicit parallel descent).
func dethunkMapWithBreadthFirstTraversal(finalResults map[string]interface{}) {
dethunkQueue := &dethunkQueue{DethunkFuncs: []func(){}}
dethunkMapBreadthFirst(finalResults, dethunkQueue)
for len(dethunkQueue.DethunkFuncs) > 0 {
f := dethunkQueue.shift()
f()
}
}
func dethunkMapBreadthFirst(m map[string]interface{}, dethunkQueue *dethunkQueue) {
for k, v := range m {
if f, ok := v.(func() interface{}); ok {
m[k] = f()
}
switch val := m[k].(type) {
case map[string]interface{}:
dethunkQueue.push(func() { dethunkMapBreadthFirst(val, dethunkQueue) })
case []interface{}:
dethunkQueue.push(func() { dethunkListBreadthFirst(val, dethunkQueue) })
}
}
}
func dethunkListBreadthFirst(list []interface{}, dethunkQueue *dethunkQueue) {
for i, v := range list {
if f, ok := v.(func() interface{}); ok {
list[i] = f()
}
switch val := list[i].(type) {
case map[string]interface{}:
dethunkQueue.push(func() { dethunkMapBreadthFirst(val, dethunkQueue) })
case []interface{}:
dethunkQueue.push(func() { dethunkListBreadthFirst(val, dethunkQueue) })
}
}
}
// dethunkMapDepthFirst performs a serial descent of the map, calling any thunks
// in the map values and replacing each thunk with that thunk's return value. This is needed
// to conform to the graphql-js reference implementation, which requires serial (depth-first)
// implementations for mutation selects.
func dethunkMapDepthFirst(m map[string]interface{}) {
for k, v := range m {
if f, ok := v.(func() interface{}); ok {
m[k] = f()
}
switch val := m[k].(type) {
case map[string]interface{}:
dethunkMapDepthFirst(val)
case []interface{}:
dethunkListDepthFirst(val)
}
}
}
func dethunkListDepthFirst(list []interface{}) {
for i, v := range list {
if f, ok := v.(func() interface{}); ok {
list[i] = f()
}
switch val := list[i].(type) {
case map[string]interface{}:
dethunkMapDepthFirst(val)
case []interface{}:
dethunkListDepthFirst(val)
}
}
}
type collectFieldsParams struct {
ExeContext *executionContext
RuntimeType *Object // previously known as OperationType
SelectionSet *ast.SelectionSet
Fields map[string][]*ast.Field
VisitedFragmentNames map[string]bool
}
// Given a selectionSet, adds all of the fields in that selection to
// the passed in map of fields, and returns it at the end.
// CollectFields requires the "runtime type" of an object. For a field which
// returns and Interface or Union type, the "runtime type" will be the actual
// Object type returned by that field.
func collectFields(p collectFieldsParams) (fields map[string][]*ast.Field) {
// overlying SelectionSet & Fields to fields
if p.SelectionSet == nil {
return p.Fields
}
fields = p.Fields
if fields == nil {
fields = map[string][]*ast.Field{}
}
if p.VisitedFragmentNames == nil {
p.VisitedFragmentNames = map[string]bool{}
}
for _, iSelection := range p.SelectionSet.Selections {
switch selection := iSelection.(type) {
case *ast.Field:
if !shouldIncludeNode(p.ExeContext, selection.Directives) {
continue
}
name := getFieldEntryKey(selection)
if _, ok := fields[name]; !ok {
fields[name] = []*ast.Field{}
}
fields[name] = append(fields[name], selection)
case *ast.InlineFragment:
if !shouldIncludeNode(p.ExeContext, selection.Directives) ||
!doesFragmentConditionMatch(p.ExeContext, selection, p.RuntimeType) {
continue
}
innerParams := collectFieldsParams{
ExeContext: p.ExeContext,
RuntimeType: p.RuntimeType,
SelectionSet: selection.SelectionSet,
Fields: fields,
VisitedFragmentNames: p.VisitedFragmentNames,
}
collectFields(innerParams)
case *ast.FragmentSpread:
fragName := ""
if selection.Name != nil {
fragName = selection.Name.Value
}
if visited, ok := p.VisitedFragmentNames[fragName]; (ok && visited) ||
!shouldIncludeNode(p.ExeContext, selection.Directives) {
continue
}
p.VisitedFragmentNames[fragName] = true
fragment, hasFragment := p.ExeContext.Fragments[fragName]
if !hasFragment {
continue
}
if fragment, ok := fragment.(*ast.FragmentDefinition); ok {
if !doesFragmentConditionMatch(p.ExeContext, fragment, p.RuntimeType) {
continue
}
innerParams := collectFieldsParams{
ExeContext: p.ExeContext,
RuntimeType: p.RuntimeType,
SelectionSet: fragment.GetSelectionSet(),
Fields: fields,
VisitedFragmentNames: p.VisitedFragmentNames,
}
collectFields(innerParams)
}
}
}
return fields
}
// Determines if a field should be included based on the @include and @skip
// directives, where @skip has higher precedence than @include.
func shouldIncludeNode(eCtx *executionContext, directives []*ast.Directive) bool {
var (
skipAST, includeAST *ast.Directive
argValues map[string]interface{}
)
for _, directive := range directives {
if directive == nil || directive.Name == nil {
continue
}
switch directive.Name.Value {
case SkipDirective.Name:
skipAST = directive
case IncludeDirective.Name:
includeAST = directive
}
}
// precedence: skipAST > includeAST
if skipAST != nil {
argValues = getArgumentValues(SkipDirective.Args, skipAST.Arguments, eCtx.VariableValues)
if skipIf, ok := argValues["if"].(bool); ok && skipIf {
return false // excluded selectionSet's fields
}
}
if includeAST != nil {
argValues = getArgumentValues(IncludeDirective.Args, includeAST.Arguments, eCtx.VariableValues)
if includeIf, ok := argValues["if"].(bool); ok && !includeIf {
return false // excluded selectionSet's fields
}
}
return true
}
// Determines if a fragment is applicable to the given type.
func doesFragmentConditionMatch(eCtx *executionContext, fragment ast.Node, ttype *Object) bool {
switch fragment := fragment.(type) {
case *ast.FragmentDefinition:
typeConditionAST := fragment.TypeCondition
if typeConditionAST == nil {
return true
}
conditionalType, err := typeFromAST(eCtx.Schema, typeConditionAST)
if err != nil {
return false
}
if conditionalType == ttype {
return true
}
if conditionalType.Name() == ttype.Name() {
return true
}
if conditionalType, ok := conditionalType.(*Interface); ok {
return eCtx.Schema.IsPossibleType(conditionalType, ttype)
}
if conditionalType, ok := conditionalType.(*Union); ok {
return eCtx.Schema.IsPossibleType(conditionalType, ttype)
}
case *ast.InlineFragment:
typeConditionAST := fragment.TypeCondition
if typeConditionAST == nil {
return true
}
conditionalType, err := typeFromAST(eCtx.Schema, typeConditionAST)
if err != nil {
return false
}
if conditionalType == ttype {
return true
}
if conditionalType.Name() == ttype.Name() {
return true
}
if conditionalType, ok := conditionalType.(*Interface); ok {
return eCtx.Schema.IsPossibleType(conditionalType, ttype)
}
if conditionalType, ok := conditionalType.(*Union); ok {
return eCtx.Schema.IsPossibleType(conditionalType, ttype)
}
}
return false
}
// Implements the logic to compute the key of a given field’s entry
func getFieldEntryKey(node *ast.Field) string {
if node.Alias != nil && node.Alias.Value != "" {
return node.Alias.Value
}
if node.Name != nil && node.Name.Value != "" {
return node.Name.Value
}
return ""
}
// Internal resolveField state
type resolveFieldResultState struct {
hasNoFieldDefs bool
}
func handleFieldError(r interface{}, fieldNodes []ast.Node, path *ResponsePath, returnType Output, eCtx *executionContext) {
err := NewLocatedErrorWithPath(r, fieldNodes, path.AsArray())
// send panic upstream
if _, ok := returnType.(*NonNull); ok {
panic(err)
}
eCtx.Errors = append(eCtx.Errors, gqlerrors.FormatError(err))
}
// Resolves the field on the given source object. In particular, this
// figures out the value that the field returns by calling its resolve function,
// then calls completeValue to complete promises, serialize scalars, or execute
// the sub-selection-set for objects.
func resolveField(eCtx *executionContext, parentType *Object, source interface{}, fieldASTs []*ast.Field, path *ResponsePath) (result interface{}, resultState resolveFieldResultState) {
// catch panic from resolveFn
var returnType Output
defer func() (interface{}, resolveFieldResultState) {
if r := recover(); r != nil {
handleFieldError(r, FieldASTsToNodeASTs(fieldASTs), path, returnType, eCtx)
return result, resultState
}
return result, resultState
}()
fieldAST := fieldASTs[0]
fieldName := ""
if fieldAST.Name != nil {
fieldName = fieldAST.Name.Value
}
fieldDef := getFieldDef(eCtx.Schema, parentType, fieldName)
if fieldDef == nil {
resultState.hasNoFieldDefs = true
return nil, resultState
}
returnType = fieldDef.Type
resolveFn := fieldDef.Resolve
if resolveFn == nil {
resolveFn = DefaultResolveFn
}
// Build a map of arguments from the field.arguments AST, using the
// variables scope to fulfill any variable references.
// TODO: find a way to memoize, in case this field is within a List type.
args := getArgumentValues(fieldDef.Args, fieldAST.Arguments, eCtx.VariableValues)
info := ResolveInfo{
FieldName: fieldName,
FieldASTs: fieldASTs,
Path: path,
ReturnType: returnType,
ParentType: parentType,
Schema: eCtx.Schema,
Fragments: eCtx.Fragments,
RootValue: eCtx.Root,
Operation: eCtx.Operation,
VariableValues: eCtx.VariableValues,
}
var resolveFnError error
extErrs, resolveFieldFinishFn := handleExtensionsResolveFieldDidStart(eCtx.Schema.extensions, eCtx, &info)
if len(extErrs) != 0 {
eCtx.Errors = append(eCtx.Errors, extErrs...)
}
result, resolveFnError = resolveFn(ResolveParams{
Source: source,
Args: args,
Info: info,
Context: eCtx.Context,
})
extErrs = resolveFieldFinishFn(result, resolveFnError)
if len(extErrs) != 0 {
eCtx.Errors = append(eCtx.Errors, extErrs...)
}
if resolveFnError != nil {
panic(resolveFnError)
}
completed := completeValueCatchingError(eCtx, returnType, fieldASTs, info, path, result)
return completed, resultState
}
func completeValueCatchingError(eCtx *executionContext, returnType Type, fieldASTs []*ast.Field, info ResolveInfo, path *ResponsePath, result interface{}) (completed interface{}) {
// catch panic
defer func() interface{} {
if r := recover(); r != nil {
handleFieldError(r, FieldASTsToNodeASTs(fieldASTs), path, returnType, eCtx)
return completed
}
return completed
}()
if returnType, ok := returnType.(*NonNull); ok {
completed := completeValue(eCtx, returnType, fieldASTs, info, path, result)
return completed
}
completed = completeValue(eCtx, returnType, fieldASTs, info, path, result)
return completed
}
func completeValue(eCtx *executionContext, returnType Type, fieldASTs []*ast.Field, info ResolveInfo, path *ResponsePath, result interface{}) interface{} {
resultVal := reflect.ValueOf(result)
if resultVal.IsValid() && resultVal.Kind() == reflect.Func {
return func() interface{} {
return completeThunkValueCatchingError(eCtx, returnType, fieldASTs, info, path, result)
}
}
// If field type is NonNull, complete for inner type, and throw field error
// if result is null.
if returnType, ok := returnType.(*NonNull); ok {
completed := completeValue(eCtx, returnType.OfType, fieldASTs, info, path, result)
if completed == nil {
err := NewLocatedErrorWithPath(
fmt.Sprintf("Cannot return null for non-nullable field %v.%v.", info.ParentType, info.FieldName),
FieldASTsToNodeASTs(fieldASTs),
path.AsArray(),
)
panic(gqlerrors.FormatError(err))
}
return completed
}
// If result value is null-ish (null, undefined, or NaN) then return null.
if isNullish(result) {
return nil
}
// If field type is List, complete each item in the list with the inner type
if returnType, ok := returnType.(*List); ok {
return completeListValue(eCtx, returnType, fieldASTs, info, path, result)
}
// If field type is a leaf type, Scalar or Enum, serialize to a valid value,
// returning null if serialization is not possible.
if returnType, ok := returnType.(*Scalar); ok {
return completeLeafValue(returnType, result)
}
if returnType, ok := returnType.(*Enum); ok {
return completeLeafValue(returnType, result)
}
// If field type is an abstract type, Interface or Union, determine the
// runtime Object type and complete for that type.
if returnType, ok := returnType.(*Union); ok {
return completeAbstractValue(eCtx, returnType, fieldASTs, info, path, result)
}
if returnType, ok := returnType.(*Interface); ok {
return completeAbstractValue(eCtx, returnType, fieldASTs, info, path, result)
}
// If field type is Object, execute and complete all sub-selections.
if returnType, ok := returnType.(*Object); ok {
return completeObjectValue(eCtx, returnType, fieldASTs, info, path, result)
}
// Not reachable. All possible output types have been considered.
err := invariantf(false,
`Cannot complete value of unexpected type "%v."`, returnType)
if err != nil {
panic(gqlerrors.FormatError(err))
}
return nil
}
func completeThunkValueCatchingError(eCtx *executionContext, returnType Type, fieldASTs []*ast.Field, info ResolveInfo, path *ResponsePath, result interface{}) (completed interface{}) {
// catch any panic invoked from the propertyFn (thunk)
defer func() {
if r := recover(); r != nil {
handleFieldError(r, FieldASTsToNodeASTs(fieldASTs), path, returnType, eCtx)
}
}()
propertyFn, ok := result.(func() (interface{}, error))
if !ok {
err := gqlerrors.NewFormattedError("Error resolving func. Expected `func() (interface{}, error)` signature")
panic(gqlerrors.FormatError(err))
}
fnResult, err := propertyFn()
if err != nil {
panic(gqlerrors.FormatError(err))
}
result = fnResult
if returnType, ok := returnType.(*NonNull); ok {
completed := completeValue(eCtx, returnType, fieldASTs, info, path, result)
return completed
}
completed = completeValue(eCtx, returnType, fieldASTs, info, path, result)
return completed
}
// completeAbstractValue completes value of an Abstract type (Union / Interface) by determining the runtime type
// of that value, then completing based on that type.
func completeAbstractValue(eCtx *executionContext, returnType Abstract, fieldASTs []*ast.Field, info ResolveInfo, path *ResponsePath, result interface{}) interface{} {
var runtimeType *Object
resolveTypeParams := ResolveTypeParams{
Value: result,
Info: info,
Context: eCtx.Context,
}
if unionReturnType, ok := returnType.(*Union); ok && unionReturnType.ResolveType != nil {
runtimeType = unionReturnType.ResolveType(resolveTypeParams)
} else if interfaceReturnType, ok := returnType.(*Interface); ok && interfaceReturnType.ResolveType != nil {
runtimeType = interfaceReturnType.ResolveType(resolveTypeParams)
} else {
runtimeType = defaultResolveTypeFn(resolveTypeParams, returnType)
}
err := invariant(runtimeType != nil,
fmt.Sprintf(`Abstract type %v must resolve to an Object type at runtime `+
`for field %v.%v with value "%v", received "%v".`,
returnType, info.ParentType, info.FieldName, result, runtimeType),
)
if err != nil {
panic(err)
}
if !eCtx.Schema.IsPossibleType(returnType, runtimeType) {
panic(gqlerrors.NewFormattedError(
fmt.Sprintf(`Runtime Object type "%v" is not a possible type `+
`for "%v".`, runtimeType, returnType),
))
}
return completeObjectValue(eCtx, runtimeType, fieldASTs, info, path, result)
}
// completeObjectValue complete an Object value by executing all sub-selections.
func completeObjectValue(eCtx *executionContext, returnType *Object, fieldASTs []*ast.Field, info ResolveInfo, path *ResponsePath, result interface{}) interface{} {
// If there is an isTypeOf predicate function, call it with the
// current result. If isTypeOf returns false, then raise an error rather
// than continuing execution.
if returnType.IsTypeOf != nil {
p := IsTypeOfParams{
Value: result,
Info: info,
Context: eCtx.Context,
}
if !returnType.IsTypeOf(p) {
panic(gqlerrors.NewFormattedError(
fmt.Sprintf(`Expected value of type "%v" but got: %T.`, returnType, result),
))
}
}
// Collect sub-fields to execute to complete this value.
subFieldASTs := map[string][]*ast.Field{}
visitedFragmentNames := map[string]bool{}
for _, fieldAST := range fieldASTs {
if fieldAST == nil {
continue
}
selectionSet := fieldAST.SelectionSet
if selectionSet != nil {
innerParams := collectFieldsParams{
ExeContext: eCtx,
RuntimeType: returnType,
SelectionSet: selectionSet,
Fields: subFieldASTs,
VisitedFragmentNames: visitedFragmentNames,
}
subFieldASTs = collectFields(innerParams)
}
}
executeFieldsParams := executeFieldsParams{
ExecutionContext: eCtx,
ParentType: returnType,
Source: result,
Fields: subFieldASTs,
Path: path,
}
return executeSubFields(executeFieldsParams)
}
// completeLeafValue complete a leaf value (Scalar / Enum) by serializing to a valid value, returning nil if serialization is not possible.
func completeLeafValue(returnType Leaf, result interface{}) interface{} {
serializedResult := returnType.Serialize(result)
if isNullish(serializedResult) {
return nil
}
return serializedResult
}
// completeListValue complete a list value by completing each item in the list with the inner type
func completeListValue(eCtx *executionContext, returnType *List, fieldASTs []*ast.Field, info ResolveInfo, path *ResponsePath, result interface{}) interface{} {
resultVal := reflect.ValueOf(result)
if resultVal.Kind() == reflect.Ptr {
resultVal = resultVal.Elem()
}
parentTypeName := ""
if info.ParentType != nil {
parentTypeName = info.ParentType.Name()
}
err := invariantf(
resultVal.IsValid() && isIterable(result),
"User Error: expected iterable, but did not find one "+
"for field %v.%v.", parentTypeName, info.FieldName)
if err != nil {
panic(gqlerrors.FormatError(err))
}
itemType := returnType.OfType
completedResults := make([]interface{}, 0, resultVal.Len())
for i := 0; i < resultVal.Len(); i++ {
val := resultVal.Index(i).Interface()
fieldPath := path.WithKey(i)
completedItem := completeValueCatchingError(eCtx, itemType, fieldASTs, info, fieldPath, val)
completedResults = append(completedResults, completedItem)
}
return completedResults
}
// defaultResolveTypeFn If a resolveType function is not given, then a default resolve behavior is
// used which tests each possible type for the abstract type by calling
// isTypeOf for the object being coerced, returning the first type that matches.
func defaultResolveTypeFn(p ResolveTypeParams, abstractType Abstract) *Object {
possibleTypes := p.Info.Schema.PossibleTypes(abstractType)
for _, possibleType := range possibleTypes {
if possibleType.IsTypeOf == nil {
continue
}
isTypeOfParams := IsTypeOfParams{
Value: p.Value,
Info: p.Info,
Context: p.Context,
}
if res := possibleType.IsTypeOf(isTypeOfParams); res {
return possibleType
}
}
return nil
}
// FieldResolver is used in DefaultResolveFn when the the source value implements this interface.
type FieldResolver interface {
// Resolve resolves the value for the given ResolveParams. It has the same semantics as FieldResolveFn.
Resolve(p ResolveParams) (interface{}, error)
}
// DefaultResolveFn If a resolve function is not given, then a default resolve behavior is used
// which takes the property of the source object of the same name as the field
// and returns it as the result, or if it's a function, returns the result
// of calling that function.
func DefaultResolveFn(p ResolveParams) (interface{}, error) {
sourceVal := reflect.ValueOf(p.Source)
// Check if value implements 'Resolver' interface
if resolver, ok := sourceVal.Interface().(FieldResolver); ok {
return resolver.Resolve(p)
}
// try to resolve p.Source as a struct
if sourceVal.IsValid() && sourceVal.Type().Kind() == reflect.Ptr {
sourceVal = sourceVal.Elem()
}
if !sourceVal.IsValid() {
return nil, nil
}
if sourceVal.Type().Kind() == reflect.Struct {
for i := 0; i < sourceVal.NumField(); i++ {
valueField := sourceVal.Field(i)
typeField := sourceVal.Type().Field(i)
// try matching the field name first
if strings.EqualFold(typeField.Name, p.Info.FieldName) {
return valueField.Interface(), nil
}
tag := typeField.Tag
checkTag := func(tagName string) bool {
t := tag.Get(tagName)
tOptions := strings.Split(t, ",")
if len(tOptions) == 0 {
return false
}
if tOptions[0] != p.Info.FieldName {
return false
}
return true
}
if checkTag("json") || checkTag("graphql") {
return valueField.Interface(), nil
} else {
continue
}
}
return nil, nil
}
// try p.Source as a map[string]interface
if sourceMap, ok := p.Source.(map[string]interface{}); ok {
property := sourceMap[p.Info.FieldName]
val := reflect.ValueOf(property)
if val.IsValid() && val.Type().Kind() == reflect.Func {
// try type casting the func to the most basic func signature
// for more complex signatures, user have to define ResolveFn
if propertyFn, ok := property.(func() interface{}); ok {
return propertyFn(), nil
}
}
return property, nil
}
// Try accessing as map via reflection
if r := reflect.ValueOf(p.Source); r.Kind() == reflect.Map && r.Type().Key().Kind() == reflect.String {
val := r.MapIndex(reflect.ValueOf(p.Info.FieldName))