-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathexecute.ts
2793 lines (2559 loc) · 80.4 KB
/
execute.ts
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 { BoxedPromiseOrValue } from '../jsutils/BoxedPromiseOrValue.js';
import { inspect } from '../jsutils/inspect.js';
import { invariant } from '../jsutils/invariant.js';
import { isAsyncIterable } from '../jsutils/isAsyncIterable.js';
import { isIterableObject } from '../jsutils/isIterableObject.js';
import { isObjectLike } from '../jsutils/isObjectLike.js';
import { isPromise } from '../jsutils/isPromise.js';
import type { Maybe } from '../jsutils/Maybe.js';
import { memoize3 } from '../jsutils/memoize3.js';
import type { ObjMap } from '../jsutils/ObjMap.js';
import type { Path } from '../jsutils/Path.js';
import { addPath, pathToArray } from '../jsutils/Path.js';
import { promiseForObject } from '../jsutils/promiseForObject.js';
import type { PromiseOrValue } from '../jsutils/PromiseOrValue.js';
import { promiseReduce } from '../jsutils/promiseReduce.js';
import { GraphQLError } from '../error/GraphQLError.js';
import { locatedError } from '../error/locatedError.js';
import type {
DocumentNode,
FieldNode,
FragmentDefinitionNode,
OperationDefinitionNode,
} from '../language/ast.js';
import { OperationTypeNode } from '../language/ast.js';
import { Kind } from '../language/kinds.js';
import type {
GraphQLAbstractType,
GraphQLField,
GraphQLFieldResolver,
GraphQLLeafType,
GraphQLList,
GraphQLObjectType,
GraphQLOutputType,
GraphQLResolveInfo,
GraphQLTypeResolver,
} from '../type/definition.js';
import {
isAbstractType,
isLeafType,
isListType,
isNonNullType,
isObjectType,
} from '../type/definition.js';
import {
GraphQLDisableErrorPropagationDirective,
GraphQLStreamDirective,
} from '../type/directives.js';
import type { GraphQLSchema } from '../type/schema.js';
import { assertValidSchema } from '../type/validate.js';
import {
AbortSignalListener,
cancellableIterable,
cancellablePromise,
} from './AbortSignalListener.js';
import type { DeferUsageSet, ExecutionPlan } from './buildExecutionPlan.js';
import { buildExecutionPlan } from './buildExecutionPlan.js';
import type {
DeferUsage,
FieldDetailsList,
FragmentDetails,
GroupedFieldSet,
} from './collectFields.js';
import {
collectFields,
collectSubfields as _collectSubfields,
} from './collectFields.js';
import { getVariableSignature } from './getVariableSignature.js';
import { buildIncrementalResponse } from './IncrementalPublisher.js';
import { mapAsyncIterable } from './mapAsyncIterable.js';
import type {
CancellableStreamRecord,
CompletedExecutionGroup,
ExecutionResult,
ExperimentalIncrementalExecutionResults,
IncrementalDataRecord,
PendingExecutionGroup,
StreamItemRecord,
StreamItemResult,
StreamRecord,
} from './types.js';
import { DeferredFragmentRecord } from './types.js';
import type { VariableValues } from './values.js';
import {
experimentalGetArgumentValues,
getArgumentValues,
getDirectiveValues,
getVariableValues,
} from './values.js';
/* eslint-disable @typescript-eslint/max-params */
// This file contains a lot of such errors but we plan to refactor it anyway
// so just disable it for entire file.
/**
* A memoized collection of relevant subfields with regard to the return
* type. Memoizing ensures the subfields are not repeatedly calculated, which
* saves overhead when resolving lists of values.
*/
const collectSubfields = memoize3(
(
validatedExecutionArgs: ValidatedExecutionArgs,
returnType: GraphQLObjectType,
fieldDetailsList: FieldDetailsList,
) => {
const { schema, fragments, variableValues, hideSuggestions } =
validatedExecutionArgs;
return _collectSubfields(
schema,
fragments,
variableValues,
returnType,
fieldDetailsList,
hideSuggestions,
);
},
);
/**
* 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
*/
export interface ValidatedExecutionArgs {
schema: GraphQLSchema;
// TODO: consider deprecating/removing fragmentDefinitions if/when fragment
// arguments are officially supported and/or the full fragment details are
// exposed within GraphQLResolveInfo.
fragmentDefinitions: ObjMap<FragmentDefinitionNode>;
fragments: ObjMap<FragmentDetails>;
rootValue: unknown;
contextValue: unknown;
operation: OperationDefinitionNode;
variableValues: VariableValues;
fieldResolver: GraphQLFieldResolver<any, any>;
typeResolver: GraphQLTypeResolver<any, any>;
subscribeFieldResolver: GraphQLFieldResolver<any, any>;
perEventExecutor: (
validatedExecutionArgs: ValidatedExecutionArgs,
) => PromiseOrValue<ExecutionResult>;
enableEarlyExecution: boolean;
hideSuggestions: boolean;
abortSignal: AbortSignal | undefined;
}
export interface ExecutionContext {
validatedExecutionArgs: ValidatedExecutionArgs;
errors: Array<GraphQLError> | undefined;
abortSignalListener: AbortSignalListener | undefined;
completed: boolean;
cancellableStreams: Set<CancellableStreamRecord> | undefined;
errorPropagation: boolean;
}
interface IncrementalContext {
errors: Array<GraphQLError> | undefined;
completed: boolean;
deferUsageSet?: DeferUsageSet | undefined;
}
export interface ExecutionArgs {
schema: GraphQLSchema;
document: DocumentNode;
rootValue?: unknown;
contextValue?: unknown;
variableValues?: Maybe<{ readonly [variable: string]: unknown }>;
operationName?: Maybe<string>;
fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;
typeResolver?: Maybe<GraphQLTypeResolver<any, any>>;
subscribeFieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;
perEventExecutor?: Maybe<
(
validatedExecutionArgs: ValidatedExecutionArgs,
) => PromiseOrValue<ExecutionResult>
>;
enableEarlyExecution?: Maybe<boolean>;
hideSuggestions?: Maybe<boolean>;
abortSignal?: Maybe<AbortSignal>;
}
export interface StreamUsage {
label: string | undefined;
initialCount: number;
fieldDetailsList: FieldDetailsList;
}
interface GraphQLWrappedResult<T> {
rawResult: T;
incrementalDataRecords: Array<IncrementalDataRecord> | undefined;
}
const UNEXPECTED_EXPERIMENTAL_DIRECTIVES =
'The provided schema unexpectedly contains experimental directives (@defer or @stream). These directives may only be utilized if experimental execution features are explicitly enabled.';
const UNEXPECTED_MULTIPLE_PAYLOADS =
'Executing this GraphQL operation would unexpectedly produce multiple payloads (due to @defer or @stream directive)';
/**
* Implements the "Executing requests" section of the GraphQL specification.
*
* Returns either a synchronous ExecutionResult (if all encountered resolvers
* are synchronous), or a Promise of an ExecutionResult that will eventually be
* resolved and never rejected.
*
* If the arguments to this function do not result in a legal execution context,
* a GraphQLError will be thrown immediately explaining the invalid input.
*
* This function does not support incremental delivery (`@defer` and `@stream`).
* If an operation which would defer or stream data is executed with this
* function, it will throw or return a rejected promise.
* Use `experimentalExecuteIncrementally` if you want to support incremental
* delivery.
*/
export function execute(args: ExecutionArgs): PromiseOrValue<ExecutionResult> {
if (args.schema.getDirective('defer') || args.schema.getDirective('stream')) {
throw new Error(UNEXPECTED_EXPERIMENTAL_DIRECTIVES);
}
const result = experimentalExecuteIncrementally(args);
// Multiple payloads could be encountered if the operation contains @defer or
// @stream directives and is not validated prior to execution
return ensureSinglePayload(result);
}
function ensureSinglePayload(
result: PromiseOrValue<
ExecutionResult | ExperimentalIncrementalExecutionResults
>,
): PromiseOrValue<ExecutionResult> {
if (isPromise(result)) {
return result.then((resolved) => {
if ('initialResult' in resolved) {
throw new Error(UNEXPECTED_MULTIPLE_PAYLOADS);
}
return resolved;
});
}
if ('initialResult' in result) {
throw new Error(UNEXPECTED_MULTIPLE_PAYLOADS);
}
return result;
}
/**
* Implements the "Executing requests" section of the GraphQL specification,
* including `@defer` and `@stream` as proposed in
* https://github.com/graphql/graphql-spec/pull/742
*
* This function returns a Promise of an ExperimentalIncrementalExecutionResults
* object. This object either consists of a single ExecutionResult, or an
* object containing an `initialResult` and a stream of `subsequentResults`.
*
* If the arguments to this function do not result in a legal execution context,
* a GraphQLError will be thrown immediately explaining the invalid input.
*/
export function experimentalExecuteIncrementally(
args: ExecutionArgs,
): PromiseOrValue<ExecutionResult | ExperimentalIncrementalExecutionResults> {
// If a valid execution context cannot be created due to incorrect arguments,
// a "Response" with only errors is returned.
const validatedExecutionArgs = validateExecutionArgs(args);
// Return early errors if execution context failed.
if (!('schema' in validatedExecutionArgs)) {
return { errors: validatedExecutionArgs };
}
return experimentalExecuteQueryOrMutationOrSubscriptionEvent(
validatedExecutionArgs,
);
}
/**
* Implements the "Executing operations" section of the spec.
*
* Returns a Promise that will eventually resolve to the data described by
* The "Response" section of the GraphQL specification.
*
* If errors are encountered while executing a GraphQL field, only that
* field and its descendants will be omitted, and sibling fields will still
* be executed. An execution which encounters errors will still result in a
* resolved Promise.
*
* Errors from sub-fields of a NonNull type may propagate to the top level,
* at which point we still log the error and null the parent field, which
* in this case is the entire response.
*/
export function executeQueryOrMutationOrSubscriptionEvent(
validatedExecutionArgs: ValidatedExecutionArgs,
): PromiseOrValue<ExecutionResult> {
const result = experimentalExecuteQueryOrMutationOrSubscriptionEvent(
validatedExecutionArgs,
);
return ensureSinglePayload(result);
}
function errorPropagation(operation: OperationDefinitionNode): boolean {
const directiveNode = operation.directives?.find(
(directive) =>
directive.name.value === GraphQLDisableErrorPropagationDirective.name,
);
return directiveNode === undefined;
}
export function experimentalExecuteQueryOrMutationOrSubscriptionEvent(
validatedExecutionArgs: ValidatedExecutionArgs,
): PromiseOrValue<ExecutionResult | ExperimentalIncrementalExecutionResults> {
const abortSignal = validatedExecutionArgs.abortSignal;
const exeContext: ExecutionContext = {
validatedExecutionArgs,
errors: undefined,
abortSignalListener: abortSignal
? new AbortSignalListener(abortSignal)
: undefined,
completed: false,
cancellableStreams: undefined,
errorPropagation: errorPropagation(validatedExecutionArgs.operation),
};
try {
const {
schema,
fragments,
rootValue,
operation,
variableValues,
hideSuggestions,
} = validatedExecutionArgs;
const { operation: operationType, selectionSet } = operation;
const rootType = schema.getRootType(operationType);
if (rootType == null) {
throw new GraphQLError(
`Schema is not configured to execute ${operationType} operation.`,
{ nodes: operation },
);
}
const { groupedFieldSet, newDeferUsages } = collectFields(
schema,
fragments,
variableValues,
rootType,
selectionSet,
hideSuggestions,
);
const graphqlWrappedResult = executeRootExecutionPlan(
exeContext,
operation.operation,
rootType,
rootValue,
groupedFieldSet,
newDeferUsages,
);
if (isPromise(graphqlWrappedResult)) {
return graphqlWrappedResult.then(
(resolved) => {
exeContext.completed = true;
return buildDataResponse(exeContext, resolved);
},
(error: unknown) => {
exeContext.completed = true;
exeContext.abortSignalListener?.disconnect();
return {
data: null,
errors: withError(exeContext.errors, error as GraphQLError),
};
},
);
}
exeContext.completed = true;
return buildDataResponse(exeContext, graphqlWrappedResult);
} catch (error) {
exeContext.completed = true;
// TODO: add test case for synchronous null bubbling to root with cancellation
/* c8 ignore next */
exeContext.abortSignalListener?.disconnect();
return { data: null, errors: withError(exeContext.errors, error) };
}
}
function withError(
errors: Array<GraphQLError> | undefined,
error: GraphQLError,
): ReadonlyArray<GraphQLError> {
return errors === undefined ? [error] : [...errors, error];
}
function buildDataResponse(
exeContext: ExecutionContext,
graphqlWrappedResult: GraphQLWrappedResult<ObjMap<unknown>>,
): ExecutionResult | ExperimentalIncrementalExecutionResults {
const { rawResult: data, incrementalDataRecords } = graphqlWrappedResult;
const errors = exeContext.errors;
if (incrementalDataRecords === undefined) {
exeContext.abortSignalListener?.disconnect();
return errors !== undefined ? { errors, data } : { data };
}
return buildIncrementalResponse(
exeContext,
data,
errors,
incrementalDataRecords,
);
}
/**
* Also implements the "Executing requests" section of the GraphQL specification.
* However, it guarantees to complete synchronously (or throw an error) assuming
* that all field resolvers are also synchronous.
*/
export function executeSync(args: ExecutionArgs): ExecutionResult {
const result = experimentalExecuteIncrementally(args);
// Assert that the execution was synchronous.
if (isPromise(result) || 'initialResult' in result) {
throw new Error('GraphQL execution failed to complete synchronously.');
}
return result;
}
/**
* 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.
*
* TODO: consider no longer exporting this function
* @internal
*/
export function validateExecutionArgs(
args: ExecutionArgs,
): ReadonlyArray<GraphQLError> | ValidatedExecutionArgs {
const {
schema,
document,
rootValue,
contextValue,
variableValues: rawVariableValues,
operationName,
fieldResolver,
typeResolver,
subscribeFieldResolver,
perEventExecutor,
enableEarlyExecution,
abortSignal,
} = args;
if (abortSignal?.aborted) {
return [locatedError(abortSignal.reason, undefined)];
}
// If the schema used for execution is invalid, throw an error.
assertValidSchema(schema);
let operation: OperationDefinitionNode | undefined;
const fragmentDefinitions: ObjMap<FragmentDefinitionNode> =
Object.create(null);
const fragments: ObjMap<FragmentDetails> = Object.create(null);
for (const definition of document.definitions) {
switch (definition.kind) {
case Kind.OPERATION_DEFINITION:
if (operationName == null) {
if (operation !== undefined) {
return [
new GraphQLError(
'Must provide operation name if query contains multiple operations.',
),
];
}
operation = definition;
} else if (definition.name?.value === operationName) {
operation = definition;
}
break;
case Kind.FRAGMENT_DEFINITION: {
fragmentDefinitions[definition.name.value] = definition;
let variableSignatures;
if (definition.variableDefinitions) {
variableSignatures = Object.create(null);
for (const varDef of definition.variableDefinitions) {
const signature = getVariableSignature(schema, varDef);
variableSignatures[signature.name] = signature;
}
}
fragments[definition.name.value] = { definition, variableSignatures };
break;
}
default:
// ignore non-executable definitions
}
}
if (!operation) {
if (operationName != null) {
return [new GraphQLError(`Unknown operation named "${operationName}".`)];
}
return [new GraphQLError('Must provide an operation.')];
}
const variableDefinitions = operation.variableDefinitions ?? [];
const hideSuggestions = args.hideSuggestions ?? false;
const variableValuesOrErrors = getVariableValues(
schema,
variableDefinitions,
rawVariableValues ?? {},
{
maxErrors: 50,
hideSuggestions,
},
);
if (variableValuesOrErrors.errors) {
return variableValuesOrErrors.errors;
}
return {
schema,
fragmentDefinitions,
fragments,
rootValue,
contextValue,
operation,
variableValues: variableValuesOrErrors.variableValues,
fieldResolver: fieldResolver ?? defaultFieldResolver,
typeResolver: typeResolver ?? defaultTypeResolver,
subscribeFieldResolver: subscribeFieldResolver ?? defaultFieldResolver,
perEventExecutor: perEventExecutor ?? executeSubscriptionEvent,
enableEarlyExecution: enableEarlyExecution === true,
hideSuggestions,
abortSignal: args.abortSignal ?? undefined,
};
}
function executeRootExecutionPlan(
exeContext: ExecutionContext,
operation: OperationTypeNode,
rootType: GraphQLObjectType,
rootValue: unknown,
originalGroupedFieldSet: GroupedFieldSet,
newDeferUsages: ReadonlyArray<DeferUsage>,
): PromiseOrValue<GraphQLWrappedResult<ObjMap<unknown>>> {
if (newDeferUsages.length === 0) {
return executeRootGroupedFieldSet(
exeContext,
operation,
rootType,
rootValue,
originalGroupedFieldSet,
undefined,
);
}
const newDeferMap = getNewDeferMap(newDeferUsages, undefined, undefined);
const { groupedFieldSet, newGroupedFieldSets } = buildExecutionPlan(
originalGroupedFieldSet,
);
const graphqlWrappedResult = executeRootGroupedFieldSet(
exeContext,
operation,
rootType,
rootValue,
groupedFieldSet,
newDeferMap,
);
if (newGroupedFieldSets.size > 0) {
const newPendingExecutionGroups = collectExecutionGroups(
exeContext,
rootType,
rootValue,
undefined,
undefined,
newGroupedFieldSets,
newDeferMap,
);
return withNewExecutionGroups(
graphqlWrappedResult,
newPendingExecutionGroups,
);
}
return graphqlWrappedResult;
}
function withNewExecutionGroups(
result: PromiseOrValue<GraphQLWrappedResult<ObjMap<unknown>>>,
newPendingExecutionGroups: ReadonlyArray<PendingExecutionGroup>,
): PromiseOrValue<GraphQLWrappedResult<ObjMap<unknown>>> {
if (isPromise(result)) {
return result.then((resolved) => {
addIncrementalDataRecords(resolved, newPendingExecutionGroups);
return resolved;
});
}
addIncrementalDataRecords(result, newPendingExecutionGroups);
return result;
}
function executeRootGroupedFieldSet(
exeContext: ExecutionContext,
operation: OperationTypeNode,
rootType: GraphQLObjectType,
rootValue: unknown,
groupedFieldSet: GroupedFieldSet,
deferMap: ReadonlyMap<DeferUsage, DeferredFragmentRecord> | undefined,
): PromiseOrValue<GraphQLWrappedResult<ObjMap<unknown>>> {
switch (operation) {
case OperationTypeNode.QUERY:
return executeFields(
exeContext,
rootType,
rootValue,
undefined,
groupedFieldSet,
undefined,
deferMap,
);
case OperationTypeNode.MUTATION:
return executeFieldsSerially(
exeContext,
rootType,
rootValue,
undefined,
groupedFieldSet,
undefined,
deferMap,
);
case OperationTypeNode.SUBSCRIPTION:
// TODO: deprecate `subscribe` and move all logic here
// Temporary solution until we finish merging execute and subscribe together
return executeFields(
exeContext,
rootType,
rootValue,
undefined,
groupedFieldSet,
undefined,
deferMap,
);
}
}
/**
* Implements the "Executing selection sets" section of the spec
* for fields that must be executed serially.
*/
function executeFieldsSerially(
exeContext: ExecutionContext,
parentType: GraphQLObjectType,
sourceValue: unknown,
path: Path | undefined,
groupedFieldSet: GroupedFieldSet,
incrementalContext: IncrementalContext | undefined,
deferMap: ReadonlyMap<DeferUsage, DeferredFragmentRecord> | undefined,
): PromiseOrValue<GraphQLWrappedResult<ObjMap<unknown>>> {
const abortSignal = exeContext.validatedExecutionArgs.abortSignal;
return promiseReduce(
groupedFieldSet,
(graphqlWrappedResult, [responseName, fieldDetailsList]) => {
const fieldPath = addPath(path, responseName, parentType.name);
if (abortSignal?.aborted) {
handleFieldError(
abortSignal.reason,
exeContext,
parentType,
fieldDetailsList,
fieldPath,
incrementalContext,
);
graphqlWrappedResult.rawResult[responseName] = null;
return graphqlWrappedResult;
}
const result = executeField(
exeContext,
parentType,
sourceValue,
fieldDetailsList,
fieldPath,
incrementalContext,
deferMap,
);
if (result === undefined) {
return graphqlWrappedResult;
}
if (isPromise(result)) {
return result.then((resolved) => {
graphqlWrappedResult.rawResult[responseName] = resolved.rawResult;
addIncrementalDataRecords(
graphqlWrappedResult,
resolved.incrementalDataRecords,
);
return graphqlWrappedResult;
});
}
graphqlWrappedResult.rawResult[responseName] = result.rawResult;
addIncrementalDataRecords(
graphqlWrappedResult,
result.incrementalDataRecords,
);
return graphqlWrappedResult;
},
{
rawResult: Object.create(null),
incrementalDataRecords: undefined,
},
);
}
function addIncrementalDataRecords(
graphqlWrappedResult: GraphQLWrappedResult<unknown>,
incrementalDataRecords: ReadonlyArray<IncrementalDataRecord> | undefined,
): void {
if (incrementalDataRecords === undefined) {
return;
}
if (graphqlWrappedResult.incrementalDataRecords === undefined) {
graphqlWrappedResult.incrementalDataRecords = [...incrementalDataRecords];
} else {
graphqlWrappedResult.incrementalDataRecords.push(...incrementalDataRecords);
}
}
/**
* Implements the "Executing selection sets" section of the spec
* for fields that may be executed in parallel.
*/
function executeFields(
exeContext: ExecutionContext,
parentType: GraphQLObjectType,
sourceValue: unknown,
path: Path | undefined,
groupedFieldSet: GroupedFieldSet,
incrementalContext: IncrementalContext | undefined,
deferMap: ReadonlyMap<DeferUsage, DeferredFragmentRecord> | undefined,
): PromiseOrValue<GraphQLWrappedResult<ObjMap<unknown>>> {
const results = Object.create(null);
const graphqlWrappedResult: GraphQLWrappedResult<ObjMap<unknown>> = {
rawResult: results,
incrementalDataRecords: undefined,
};
let containsPromise = false;
try {
for (const [responseName, fieldDetailsList] of groupedFieldSet) {
const fieldPath = addPath(path, responseName, parentType.name);
const result = executeField(
exeContext,
parentType,
sourceValue,
fieldDetailsList,
fieldPath,
incrementalContext,
deferMap,
);
if (result !== undefined) {
if (isPromise(result)) {
results[responseName] = result.then((resolved) => {
addIncrementalDataRecords(
graphqlWrappedResult,
resolved.incrementalDataRecords,
);
return resolved.rawResult;
});
containsPromise = true;
} else {
results[responseName] = result.rawResult;
addIncrementalDataRecords(
graphqlWrappedResult,
result.incrementalDataRecords,
);
}
}
}
} catch (error) {
if (containsPromise) {
// Ensure that any promises returned by other fields are handled, as they may also reject.
return promiseForObject(results, () => {
/* noop */
}).finally(() => {
throw error;
}) as never;
}
throw error;
}
// If there are no promises, we can just return the object and any incrementalDataRecords
if (!containsPromise) {
return graphqlWrappedResult;
}
// Otherwise, results is a map from field name to the result of resolving that
// field, which is possibly a promise. Return a promise that will return this
// same map, but with any promises replaced with the values they resolved to.
return promiseForObject(results, (resolved) => ({
rawResult: resolved,
incrementalDataRecords: graphqlWrappedResult.incrementalDataRecords,
}));
}
function toNodes(fieldDetailsList: FieldDetailsList): ReadonlyArray<FieldNode> {
return fieldDetailsList.map((fieldDetails) => fieldDetails.node);
}
/**
* Implements the "Executing fields" section of the spec
* In particular, this function figures out the value that the field returns by
* calling its resolve function, then calls completeValue to complete promises,
* coercing scalars, or execute the sub-selection-set for objects.
*/
function executeField(
exeContext: ExecutionContext,
parentType: GraphQLObjectType,
source: unknown,
fieldDetailsList: FieldDetailsList,
path: Path,
incrementalContext: IncrementalContext | undefined,
deferMap: ReadonlyMap<DeferUsage, DeferredFragmentRecord> | undefined,
): PromiseOrValue<GraphQLWrappedResult<unknown>> | undefined {
const { validatedExecutionArgs, abortSignalListener } = exeContext;
const { schema, contextValue, variableValues, hideSuggestions, abortSignal } =
validatedExecutionArgs;
const fieldName = fieldDetailsList[0].node.name.value;
const fieldDef = schema.getField(parentType, fieldName);
if (!fieldDef) {
return;
}
const returnType = fieldDef.type;
const resolveFn = fieldDef.resolve ?? validatedExecutionArgs.fieldResolver;
const info = buildResolveInfo(
validatedExecutionArgs,
fieldDef,
toNodes(fieldDetailsList),
parentType,
path,
);
// Get the resolve function, regardless of if its result is normal or abrupt (error).
try {
// Build a JS 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.
const args = experimentalGetArgumentValues(
fieldDetailsList[0].node,
fieldDef.args,
variableValues,
fieldDetailsList[0].fragmentVariableValues,
hideSuggestions,
);
// The resolve function's optional third argument is a context value that
// is provided to every resolve function within an execution. It is commonly
// used to represent an authenticated user, or request-specific caches.
const result = resolveFn(source, args, contextValue, info, abortSignal);
if (isPromise(result)) {
return completePromisedValue(
exeContext,
returnType,
fieldDetailsList,
info,
path,
abortSignalListener
? cancellablePromise(result, abortSignalListener)
: result,
incrementalContext,
deferMap,
);
}
const completed = completeValue(
exeContext,
returnType,
fieldDetailsList,
info,
path,
result,
incrementalContext,
deferMap,
);
if (isPromise(completed)) {
// Note: we don't rely on a `catch` method, but we do expect "thenable"
// to take a second callback for the error case.
return completed.then(undefined, (rawError: unknown) => {
handleFieldError(
rawError,
exeContext,
returnType,
fieldDetailsList,
path,
incrementalContext,
);
return { rawResult: null, incrementalDataRecords: undefined };
});
}
return completed;
} catch (rawError) {
handleFieldError(
rawError,
exeContext,
returnType,
fieldDetailsList,
path,
incrementalContext,
);
return { rawResult: null, incrementalDataRecords: undefined };
}
}
/**
* TODO: consider no longer exporting this function
* @internal
*/
export function buildResolveInfo(
validatedExecutionArgs: ValidatedExecutionArgs,
fieldDef: GraphQLField<unknown, unknown>,
fieldNodes: ReadonlyArray<FieldNode>,
parentType: GraphQLObjectType,
path: Path,
): GraphQLResolveInfo {
const { schema, fragmentDefinitions, rootValue, operation, variableValues } =
validatedExecutionArgs;
// The resolve function's optional fourth argument is a collection of
// information about the current execution state.
return {
fieldName: fieldDef.name,
fieldNodes,
returnType: fieldDef.type,
parentType,
path,
schema,
fragments: fragmentDefinitions,
rootValue,
operation,
variableValues,
};
}
function handleFieldError(
rawError: unknown,
exeContext: ExecutionContext,
returnType: GraphQLOutputType,
fieldDetailsList: FieldDetailsList,
path: Path,
incrementalContext: IncrementalContext | undefined,
): void {
const error = locatedError(
rawError,
toNodes(fieldDetailsList),
pathToArray(path),
);
// If the field type is non-nullable, then it is resolved without any
// protection from errors, however it still properly locates the error.
if (exeContext.errorPropagation && isNonNullType(returnType)) {
throw error;
}
// Otherwise, error protection is applied, logging the error and resolving
// a null value for this field if one is encountered.
const context = incrementalContext ?? exeContext;
let errors = context.errors;