/
Execute.swift
1162 lines (1032 loc) · 35.4 KB
/
Execute.swift
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
import Dispatch
/**
* Terminology
*
* "Definitions" are the generic name for top-level statements in the document.
* Examples of this include:
* 1) Operations (such as a query)
* 2) Fragments
*
* "Operations" are a generic name for requests in the document.
* Examples of this include:
* 1) query,
* 2) mutation
*
* "Selections" are the definitions that can appear legally and at
* single level of the query. These include:
* 1) field references e.g "a"
* 2) fragment "spreads" e.g. "...c"
* 3) inline fragment "spreads" e.g. "...on Type { a }"
*/
/**
* Data that must be available at all points during query execution.
*
* Namely, schema of the type system that is currently executing,
* and the fragments defined in the query document
*/
public final class ExecutionContext {
let queryStrategy: QueryFieldExecutionStrategy
let mutationStrategy: MutationFieldExecutionStrategy
let subscriptionStrategy: SubscriptionFieldExecutionStrategy
let instrumentation: Instrumentation
public let schema: GraphQLSchema
public let fragments: [String: FragmentDefinition]
public let rootValue: Any
public let contextValue: Any
public let operation: OperationDefinition
public let variableValues: [String: Map]
private var errorsSemaphore = DispatchSemaphore(value: 1)
private var _errors: [GraphQLError]
public var errors: [GraphQLError] {
get {
errorsSemaphore.wait()
defer {
errorsSemaphore.signal()
}
return _errors
}
}
init(
queryStrategy: QueryFieldExecutionStrategy,
mutationStrategy: MutationFieldExecutionStrategy,
subscriptionStrategy: SubscriptionFieldExecutionStrategy,
instrumentation: Instrumentation,
schema: GraphQLSchema,
fragments: [String: FragmentDefinition],
rootValue: Any,
contextValue: Any,
operation: OperationDefinition,
variableValues: [String: Map],
errors: [GraphQLError]
) {
self.queryStrategy = queryStrategy
self.mutationStrategy = mutationStrategy
self.subscriptionStrategy = subscriptionStrategy
self.instrumentation = instrumentation
self.schema = schema
self.fragments = fragments
self.rootValue = rootValue
self.contextValue = contextValue
self.operation = operation
self.variableValues = variableValues
self._errors = errors
}
public func append(error: GraphQLError) {
errorsSemaphore.wait()
defer {
errorsSemaphore.signal()
}
_errors.append(error)
}
}
public protocol FieldExecutionStrategy {
func executeFields(
exeContext: ExecutionContext,
parentType: GraphQLObjectType,
sourceValue: Any,
path: [IndexPathElement],
fields: [String: [Field]]
) throws -> [String: Any]
}
public protocol MutationFieldExecutionStrategy: FieldExecutionStrategy {}
public protocol QueryFieldExecutionStrategy: FieldExecutionStrategy {}
public protocol SubscriptionFieldExecutionStrategy: FieldExecutionStrategy {}
/**
* Serial field execution strategy that's suitable for the "Evaluating selection sets" section of the spec for "write" mode.
*/
public struct SerialFieldExecutionStrategy: QueryFieldExecutionStrategy, MutationFieldExecutionStrategy, SubscriptionFieldExecutionStrategy {
public init () {}
public func executeFields(
exeContext: ExecutionContext,
parentType: GraphQLObjectType,
sourceValue: Any,
path: [IndexPathElement],
fields: [String: [Field]]
) throws -> [String: Any] {
return try fields.reduce([:]) { results, field in
var results = results
let fieldASTs = field.value
let fieldPath = path + [field.key] as [IndexPathElement]
let result = try resolveField(
exeContext: exeContext,
parentType: parentType,
source: sourceValue,
fieldASTs: fieldASTs,
path: fieldPath
)
results[field.key] = result ?? Map.null
return results
}
}
}
/**
* Serial field execution strategy that's suitable for the "Evaluating selection sets" section of the spec for "read" mode.
*
* Each field is resolved as an individual task on a concurrent dispatch queue.
*/
public struct ConcurrentDispatchFieldExecutionStrategy: QueryFieldExecutionStrategy, SubscriptionFieldExecutionStrategy {
let dispatchQueue: DispatchQueue
public init(dispatchQueue: DispatchQueue) {
self.dispatchQueue = dispatchQueue
}
public init(queueLabel: String = "GraphQL field execution", queueQoS: DispatchQoS = .userInitiated) {
self.dispatchQueue = DispatchQueue(
label: queueLabel,
qos: queueQoS,
attributes: .concurrent
)
}
public func executeFields(
exeContext: ExecutionContext,
parentType: GraphQLObjectType,
sourceValue: Any,
path: [IndexPathElement],
fields: [String: [Field]]
) throws -> [String: Any] {
let resultsQueue = DispatchQueue(
label: "\(dispatchQueue.label) results",
qos: dispatchQueue.qos
)
let group = DispatchGroup()
var results: [String: Any] = [:]
var err: Error? = nil
fields.forEach { field in
let fieldASTs = field.value
let fieldKey = field.key
let fieldPath = path + [fieldKey] as [IndexPathElement]
dispatchQueue.async(group: group) {
guard err == nil else {
return
}
do {
let result = try resolveField(
exeContext: exeContext,
parentType: parentType,
source: sourceValue,
fieldASTs: fieldASTs,
path: fieldPath
)
resultsQueue.async(group: group) {
results[fieldKey] = result ?? Map.null
}
} catch {
resultsQueue.async(group: group) {
err = error
}
}
}
}
group.wait()
if let error = err {
throw error
}
return results
}
}
/**
* Implements the "Evaluating requests" section of the GraphQL specification.
*
* If the arguments to this func do not result in a legal execution context,
* a GraphQLError will be thrown immediately explaining the invalid input.
*/
func execute(
queryStrategy: QueryFieldExecutionStrategy,
mutationStrategy: MutationFieldExecutionStrategy,
subscriptionStrategy: SubscriptionFieldExecutionStrategy,
instrumentation: Instrumentation,
schema: GraphQLSchema,
documentAST: Document,
rootValue: Any,
contextValue: Any,
variableValues: [String: Map] = [:],
operationName: String? = nil
) throws -> Map {
let executeStarted = instrumentation.now
let context: ExecutionContext
do {
// If a valid context cannot be created due to incorrect arguments,
// this will throw an error.
context = try buildExecutionContext(
queryStrategy: queryStrategy,
mutationStrategy: mutationStrategy,
subscriptionStrategy: subscriptionStrategy,
instrumentation: instrumentation,
schema: schema,
documentAST: documentAST,
rootValue: rootValue,
contextValue: contextValue,
rawVariableValues: variableValues,
operationName: operationName
)
} catch let error as GraphQLError {
instrumentation.operationExecution(
processId: processId(),
threadId: threadId(),
started: executeStarted,
finished: instrumentation.now,
schema: schema,
document: documentAST,
rootValue: rootValue,
contextValue: contextValue,
variableValues: variableValues,
operation: nil,
errors: [error],
result: nil
)
throw error
}
let executeResult: Map
let executeErrors: [GraphQLError]
do {
let data = try executeOperation(
exeContext: context,
operation: context.operation,
rootValue: rootValue
)
var dataMap: Map = [:]
for (key, value) in data {
dataMap[key] = try map(from: value)
}
var result: [String: Map] = ["data": dataMap]
if !context.errors.isEmpty {
result["errors"] = context.errors.map
}
executeResult = .dictionary(result)
executeErrors = context.errors
} catch let error as GraphQLError {
executeResult = ["errors": [error].map]
executeErrors = [error]
}
instrumentation.operationExecution(
processId: processId(),
threadId: threadId(),
started: executeStarted,
finished: instrumentation.now,
schema: schema,
document: documentAST,
rootValue: rootValue,
contextValue: contextValue,
variableValues: variableValues,
operation: context.operation,
errors: executeErrors,
result: executeResult
)
return executeResult
}
/**
* Constructs a ExecutionContext object from the arguments passed to
* execute, which we will pass throughout the other execution methods.
*
* Throws a GraphQLError if a valid execution context cannot be created.
*/
func buildExecutionContext(
queryStrategy: QueryFieldExecutionStrategy,
mutationStrategy: MutationFieldExecutionStrategy,
subscriptionStrategy: SubscriptionFieldExecutionStrategy,
instrumentation: Instrumentation,
schema: GraphQLSchema,
documentAST: Document,
rootValue: Any,
contextValue: Any,
rawVariableValues: [String: Map],
operationName: String?
) throws -> ExecutionContext {
let errors: [GraphQLError] = []
var possibleOperation: OperationDefinition? = nil
var fragments: [String: FragmentDefinition] = [:]
for definition in documentAST.definitions {
switch definition {
case let definition as OperationDefinition:
guard !(operationName == nil && possibleOperation != nil) else {
throw GraphQLError(
message: "Must provide operation name if query contains multiple operations."
)
}
if operationName == nil || definition.name?.value == operationName {
possibleOperation = definition
}
case let definition as FragmentDefinition:
fragments[definition.name.value] = definition
default:
throw GraphQLError(
message: "GraphQL cannot execute a request containing a \(definition.kind).",
nodes: [definition]
)
}
}
guard let operation = possibleOperation else {
if let operationName = operationName {
throw GraphQLError(message: "Unknown operation named \"\(operationName)\".")
} else {
throw GraphQLError(message: "Must provide an operation.")
}
}
let variableValues = try getVariableValues(
schema: schema,
definitionASTs: operation.variableDefinitions,
inputs: rawVariableValues
)
return ExecutionContext(
queryStrategy: queryStrategy,
mutationStrategy: mutationStrategy,
subscriptionStrategy: subscriptionStrategy,
instrumentation: instrumentation,
schema: schema,
fragments: fragments,
rootValue: rootValue,
contextValue: contextValue,
operation: operation,
variableValues: variableValues,
errors: errors
)
}
/**
* Implements the "Evaluating operations" section of the spec.
*/
func executeOperation(
exeContext: ExecutionContext,
operation: OperationDefinition,
rootValue: Any
) throws -> [String : Any] {
let type = try getOperationRootType(schema: exeContext.schema, operation: operation)
var inputFields: [String : [Field]] = [:]
var visitedFragmentNames: [String : Bool] = [:]
let fields = try collectFields(
exeContext: exeContext,
runtimeType: type,
selectionSet: operation.selectionSet,
fields: &inputFields,
visitedFragmentNames: &visitedFragmentNames
)
let path: [IndexPathElement] = []
let fieldExecutionStrategy: FieldExecutionStrategy
switch operation.operation {
case .query:
fieldExecutionStrategy = exeContext.queryStrategy
case .mutation:
fieldExecutionStrategy = exeContext.mutationStrategy
case .subscription:
fieldExecutionStrategy = exeContext.subscriptionStrategy
}
return try fieldExecutionStrategy.executeFields(
exeContext: exeContext,
parentType: type,
sourceValue: rootValue,
path: path,
fields: fields
)
}
/**
* Extracts the root type of the operation from the schema.
*/
func getOperationRootType(
schema: GraphQLSchema,
operation: OperationDefinition
) throws -> GraphQLObjectType {
switch operation.operation {
case .query:
return schema.queryType
case .mutation:
guard let mutationType = schema.mutationType else {
throw GraphQLError(
message: "Schema is not configured for mutations",
nodes: [operation]
)
}
return mutationType
case .subscription:
guard let subscriptionType = schema.subscriptionType else {
throw GraphQLError(
message: "Schema is not configured for subscriptions",
nodes: [operation]
)
}
return subscriptionType
}
}
/**
* 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.
*/
@discardableResult
func collectFields(
exeContext: ExecutionContext,
runtimeType: GraphQLObjectType,
selectionSet: SelectionSet,
fields: inout [String: [Field]],
visitedFragmentNames: inout [String: Bool]
) throws -> [String: [Field]] {
var visitedFragmentNames = visitedFragmentNames
for selection in selectionSet.selections {
switch selection {
case let field as Field:
let shouldInclude = try shouldIncludeNode(
exeContext: exeContext,
directives: field.directives
)
guard shouldInclude else {
continue
}
let name = getFieldEntryKey(node: field)
if fields[name] == nil {
fields[name] = []
}
fields[name]?.append(field)
case let inlineFragment as InlineFragment:
let shouldInclude = try shouldIncludeNode(
exeContext: exeContext,
directives: inlineFragment.directives
)
let fragmentConditionMatches = try doesFragmentConditionMatch(
exeContext: exeContext,
fragment: inlineFragment,
type: runtimeType
)
guard shouldInclude && fragmentConditionMatches else {
continue
}
try collectFields(
exeContext: exeContext,
runtimeType: runtimeType,
selectionSet: inlineFragment.selectionSet,
fields: &fields,
visitedFragmentNames: &visitedFragmentNames
)
case let fragmentSpread as FragmentSpread:
let fragmentName = fragmentSpread.name.value
let shouldInclude = try shouldIncludeNode(
exeContext: exeContext,
directives: fragmentSpread.directives
)
guard visitedFragmentNames[fragmentName] == nil && shouldInclude else {
continue
}
visitedFragmentNames[fragmentName] = true
guard let fragment = exeContext.fragments[fragmentName] else {
continue
}
let fragmentConditionMatches = try doesFragmentConditionMatch(
exeContext: exeContext,
fragment: fragment,
type: runtimeType
)
guard fragmentConditionMatches else {
continue
}
try collectFields(
exeContext: exeContext,
runtimeType: runtimeType,
selectionSet: fragment.selectionSet,
fields: &fields,
visitedFragmentNames: &visitedFragmentNames
)
default:
break
}
}
return fields
}
/**
* Determines if a field should be included based on the @include and @skip
* directives, where @skip has higher precidence than @include.
*/
func shouldIncludeNode(exeContext: ExecutionContext, directives: [Directive] = []) throws -> Bool {
if let skipAST = directives.find({ $0.name.value == GraphQLSkipDirective.name }) {
let skip = try getArgumentValues(
argDefs: GraphQLSkipDirective.args,
argASTs: skipAST.arguments,
variableValues: exeContext.variableValues
)
if skip["if"] == .bool(true) {
return false
}
}
if let includeAST = directives.find({ $0.name.value == GraphQLIncludeDirective.name }) {
let include = try getArgumentValues(
argDefs: GraphQLIncludeDirective.args,
argASTs: includeAST.arguments,
variableValues: exeContext.variableValues
)
if include["if"] == .bool(false) {
return false
}
}
return true
}
/**
* Determines if a fragment is applicable to the given type.
*/
func doesFragmentConditionMatch(
exeContext: ExecutionContext,
fragment: HasTypeCondition,
type: GraphQLObjectType
) throws -> Bool {
guard let typeConditionAST = fragment.getTypeCondition() else {
return true
}
guard let conditionalType = typeFromAST(schema: exeContext.schema, inputTypeAST: typeConditionAST) else {
return true
}
if let conditionalType = conditionalType as? GraphQLObjectType, conditionalType.name == type.name {
return true
}
if let abstractType = conditionalType as? GraphQLAbstractType {
return try exeContext.schema.isPossibleType(abstractType: abstractType, possibleType: type)
}
return false
}
/**
* Implements the logic to compute the key of a given field's entry
*/
func getFieldEntryKey(node: Field) -> String {
return node.alias?.value ?? node.name.value
}
/**
* Resolves the field on the given source object. In particular, this
* figures out the value that the field returns by calling its resolve func,
* then calls completeValue to complete promises, serialize scalars, or execute
* the sub-selection-set for objects.
*/
public func resolveField(
exeContext: ExecutionContext,
parentType: GraphQLObjectType,
source: Any,
fieldASTs: [Field],
path: [IndexPathElement]
) throws -> Any? {
let fieldAST = fieldASTs[0]
let fieldName = fieldAST.name.value
let fieldDef = getFieldDef(
schema: exeContext.schema,
parentType: parentType,
fieldName: fieldName
)
let returnType = fieldDef.type
let resolve = fieldDef.resolve ?? defaultResolve
// Build a Map object 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.
let args = try getArgumentValues(
argDefs: fieldDef.args,
argASTs: fieldAST.arguments,
variableValues: exeContext.variableValues
)
// The resolve func's optional third argument is a context value that
// is provided to every resolve func within an execution. It is commonly
// used to represent an authenticated user, or request-specific caches.
let context = exeContext.contextValue
// The resolve func's optional fourth argument is a collection of
// information about the current execution state.
let info = GraphQLResolveInfo(
fieldName: fieldName,
fieldASTs: fieldASTs,
returnType: returnType,
parentType: parentType,
path: path,
schema: exeContext.schema,
fragments: exeContext.fragments,
rootValue: exeContext.rootValue,
operation: exeContext.operation,
variableValues: exeContext.variableValues
)
let resolveFieldStarted = exeContext.instrumentation.now
// Get the resolve func, regardless of if its result is normal
// or abrupt (error).
let result = resolveOrError(
resolve: resolve,
source: source,
args: args,
context: context,
info: info
)
exeContext.instrumentation.fieldResolution(
processId: processId(),
threadId: threadId(),
started: resolveFieldStarted,
finished: exeContext.instrumentation.now,
source: source,
args: args,
context: context,
info: info,
result: result
)
return try completeValueCatchingError(
exeContext: exeContext,
returnType: returnType,
fieldASTs: fieldASTs,
info: info,
path: path,
result: result
)
}
public enum ResultOrError<T, E> {
case result(T)
case error(E)
}
// Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField`
// function. Returns the result of `resolve` or the abrupt-return Error object.
func resolveOrError(
resolve: GraphQLFieldResolve,
source: Any,
args: Map,
context: Any,
info: GraphQLResolveInfo
)-> ResultOrError<Any?, Error> {
do {
return try .result(resolve(source, args, context, info))
} catch {
return .error(error)
}
}
// This is a small wrapper around completeValue which detects and logs errors
// in the execution context.
func completeValueCatchingError(
exeContext: ExecutionContext,
returnType: GraphQLType,
fieldASTs: [Field],
info: GraphQLResolveInfo,
path: [IndexPathElement],
result: ResultOrError<Any?, Error>
) throws -> Any? {
// If the field type is non-nullable, then it is resolved without any
// protection from errors, however it still properly locates the error.
if let returnType = returnType as? GraphQLNonNull {
return try completeValueWithLocatedError(
exeContext: exeContext,
returnType: returnType,
fieldASTs: fieldASTs,
info: info,
path: path,
result: result
)
}
// Otherwise, error protection is applied, logging the error and resolving
// a null value for this field if one is encountered.
do {
let completed = try completeValueWithLocatedError(
exeContext: exeContext,
returnType: returnType,
fieldASTs: fieldASTs,
info: info,
path: path,
result: result
)
return completed
} catch let error as GraphQLError {
// If `completeValueWithLocatedError` returned abruptly (threw an error),
// log the error and return .null.
exeContext.append(error: error)
return nil
} catch {
fatalError()
}
}
// This is a small wrapper around completeValue which annotates errors with
// location information.
func completeValueWithLocatedError(
exeContext: ExecutionContext,
returnType: GraphQLType,
fieldASTs: [Field],
info: GraphQLResolveInfo,
path: [IndexPathElement],
result: ResultOrError<Any?, Error>
) throws -> Any? {
do {
let completed = try completeValue(
exeContext: exeContext,
returnType: returnType,
fieldASTs: fieldASTs,
info: info,
path: path,
result: result
)
return completed
} catch {
throw locatedError(
originalError: error,
nodes: fieldASTs,
path: path
)
}
}
/**
* Implements the instructions for completeValue as defined in the
* "Field entries" section of the spec.
*
* If the field type is Non-Null, then this recursively completes the value
* for the inner type. It throws a field error if that completion returns null,
* as per the "Nullability" section of the spec.
*
* If the field type is a List, then this recursively completes the value
* for the inner type on each item in the list.
*
* If the field type is a Scalar or Enum, ensures the completed value is a legal
* value of the type by calling the `serialize` method of GraphQL type
* definition.
*
* If the field is an abstract type, determine the runtime type of the value
* and then complete based on that type
*
* Otherwise, the field type expects a sub-selection set, and will complete the
* value by evaluating all sub-selections.
*/
func completeValue(
exeContext: ExecutionContext,
returnType: GraphQLType,
fieldASTs: [Field],
info: GraphQLResolveInfo,
path: [IndexPathElement],
result: ResultOrError<Any?, Error>
) throws -> Any? {
switch result {
case .error(let error):
throw error
case .result(let result):
// If field type is NonNull, complete for inner type, and throw field error
// if result is nullish.
if let returnType = returnType as? GraphQLNonNull {
let completed = try completeValue(
exeContext: exeContext,
returnType: returnType.ofType,
fieldASTs: fieldASTs,
info: info,
path: path,
result: .result(result)
)
guard let reallyCompleted = completed else {
throw GraphQLError(
message: "Cannot return null for non-nullable field \(info.parentType.name).\(info.fieldName)."
)
}
return reallyCompleted
}
// If result value is null-ish (nil or .null) then return .null.
guard let res = result, let r = unwrap(res) else {
return nil
}
// If field type is List, complete each item in the list with the inner type
if let returnType = returnType as? GraphQLList {
return try completeListValue(
exeContext: exeContext,
returnType: returnType,
fieldASTs: fieldASTs,
info: info,
path: path,
result: r
)
}
// If field type is a leaf type, Scalar or Enum, serialize to a valid value,
// returning .null if serialization is not possible.
if let returnType = returnType as? GraphQLLeafType {
return try completeLeafValue(returnType: returnType, result: r)
}
// If field type is an abstract type, Interface or Union, determine the
// runtime Object type and complete for that type.
if let returnType = returnType as? GraphQLAbstractType {
return try completeAbstractValue(
exeContext: exeContext,
returnType: returnType,
fieldASTs: fieldASTs,
info: info,
path: path,
result: r
)
}
// If field type is Object, execute and complete all sub-selections.
if let returnType = returnType as? GraphQLObjectType {
return try completeObjectValue(
exeContext: exeContext,
returnType: returnType,
fieldASTs: fieldASTs,
info: info,
path: path,
result: r
)
}
// Not reachable. All possible output types have been considered.
throw GraphQLError(
message: "Cannot complete value of unexpected type \"\(returnType)\"."
)
}
}
/**
* Complete a list value by completing each item in the list with the
* inner type
*/
func completeListValue(
exeContext: ExecutionContext,
returnType: GraphQLList,
fieldASTs: [Field],
info: GraphQLResolveInfo,
path: [IndexPathElement],
result: Any
) throws -> Any? {
guard let result = result as? [Any?] else {
throw GraphQLError(
message:
"Expected array, but did not find one for field " +
"\(info.parentType.name).\(info.fieldName)."
)
}
let itemType = returnType.ofType
var completedResults: [Any?] = []
for (index, item) in result.enumerated() {
// No need to modify the info object containing the path,
// since from here on it is not ever accessed by resolver funcs.
let fieldPath = path + [index] as [IndexPathElement]
let completedItem = try completeValueCatchingError(
exeContext: exeContext,
returnType: itemType,
fieldASTs: fieldASTs,
info: info,
path: fieldPath,
result: .result(item)
)
completedResults.append(completedItem)
}
return completedResults
}
/**
* Complete a Scalar or Enum by serializing to a valid value, returning
* .null if serialization is not possible.
*/
func completeLeafValue(returnType: GraphQLLeafType, result: Any?) throws -> Map {
// TODO: check this out
guard let result = result else {
return .null
}
let serializedResult = try returnType.serialize(value: result)
if serializedResult == .null {
throw GraphQLError(
message:
"Expected a value of type \"\(returnType)\" but " +
"received: \(result)"
)
}
return serializedResult
}
/**
* Complete a value of an abstract type by determining the runtime object type
* of that value, then complete the value for that type.
*/
func completeAbstractValue(
exeContext: ExecutionContext,
returnType: GraphQLAbstractType,
fieldASTs: [Field],
info: GraphQLResolveInfo,
path: [IndexPathElement],
result: Any
) throws -> Any? {
var resolveRes = try returnType.resolveType?(result, exeContext.contextValue, info).typeResolveResult
resolveRes = try resolveRes ?? defaultResolveType(
value: result,
context: exeContext.contextValue,
info: info,
abstractType: returnType