UNPKG

30.6 kBJavaScriptView Raw
1import inspect from "../jsutils/inspect.mjs";
2import memoize3 from "../jsutils/memoize3.mjs";
3import invariant from "../jsutils/invariant.mjs";
4import devAssert from "../jsutils/devAssert.mjs";
5import isPromise from "../jsutils/isPromise.mjs";
6import isObjectLike from "../jsutils/isObjectLike.mjs";
7import safeArrayFrom from "../jsutils/safeArrayFrom.mjs";
8import promiseReduce from "../jsutils/promiseReduce.mjs";
9import promiseForObject from "../jsutils/promiseForObject.mjs";
10import { addPath, pathToArray } from "../jsutils/Path.mjs";
11import { GraphQLError } from "../error/GraphQLError.mjs";
12import { locatedError } from "../error/locatedError.mjs";
13import { Kind } from "../language/kinds.mjs";
14import { assertValidSchema } from "../type/validate.mjs";
15import { SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from "../type/introspection.mjs";
16import { GraphQLIncludeDirective, GraphQLSkipDirective } from "../type/directives.mjs";
17import { isNamedType, isObjectType, isAbstractType, isLeafType, isListType, isNonNullType } from "../type/definition.mjs";
18import { typeFromAST } from "../utilities/typeFromAST.mjs";
19import { getOperationRootType } from "../utilities/getOperationRootType.mjs";
20import { getVariableValues, getArgumentValues, getDirectiveValues } from "./values.mjs";
21/**
22 * Terminology
23 *
24 * "Definitions" are the generic name for top-level statements in the document.
25 * Examples of this include:
26 * 1) Operations (such as a query)
27 * 2) Fragments
28 *
29 * "Operations" are a generic name for requests in the document.
30 * Examples of this include:
31 * 1) query,
32 * 2) mutation
33 *
34 * "Selections" are the definitions that can appear legally and at
35 * single level of the query. These include:
36 * 1) field references e.g "a"
37 * 2) fragment "spreads" e.g. "...c"
38 * 3) inline fragment "spreads" e.g. "...on Type { a }"
39 */
40
41/**
42 * Data that must be available at all points during query execution.
43 *
44 * Namely, schema of the type system that is currently executing,
45 * and the fragments defined in the query document
46 */
47
48export function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {
49 /* eslint-enable no-redeclare */
50 // Extract arguments from object args if provided.
51 return arguments.length === 1 ? executeImpl(argsOrSchema) : executeImpl({
52 schema: argsOrSchema,
53 document: document,
54 rootValue: rootValue,
55 contextValue: contextValue,
56 variableValues: variableValues,
57 operationName: operationName,
58 fieldResolver: fieldResolver,
59 typeResolver: typeResolver
60 });
61}
62/**
63 * Also implements the "Evaluating requests" section of the GraphQL specification.
64 * However, it guarantees to complete synchronously (or throw an error) assuming
65 * that all field resolvers are also synchronous.
66 */
67
68export function executeSync(args) {
69 var result = executeImpl(args); // Assert that the execution was synchronous.
70
71 if (isPromise(result)) {
72 throw new Error('GraphQL execution failed to complete synchronously.');
73 }
74
75 return result;
76}
77
78function executeImpl(args) {
79 var schema = args.schema,
80 document = args.document,
81 rootValue = args.rootValue,
82 contextValue = args.contextValue,
83 variableValues = args.variableValues,
84 operationName = args.operationName,
85 fieldResolver = args.fieldResolver,
86 typeResolver = args.typeResolver; // If arguments are missing or incorrect, throw an error.
87
88 assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments,
89 // a "Response" with only errors is returned.
90
91 var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver); // Return early errors if execution context failed.
92
93 if (Array.isArray(exeContext)) {
94 return {
95 errors: exeContext
96 };
97 } // Return a Promise that will eventually resolve to the data described by
98 // The "Response" section of the GraphQL specification.
99 //
100 // If errors are encountered while executing a GraphQL field, only that
101 // field and its descendants will be omitted, and sibling fields will still
102 // be executed. An execution which encounters errors will still result in a
103 // resolved Promise.
104
105
106 var data = executeOperation(exeContext, exeContext.operation, rootValue);
107 return buildResponse(exeContext, data);
108}
109/**
110 * Given a completed execution context and data, build the { errors, data }
111 * response defined by the "Response" section of the GraphQL specification.
112 */
113
114
115function buildResponse(exeContext, data) {
116 if (isPromise(data)) {
117 return data.then(function (resolved) {
118 return buildResponse(exeContext, resolved);
119 });
120 }
121
122 return exeContext.errors.length === 0 ? {
123 data: data
124 } : {
125 errors: exeContext.errors,
126 data: data
127 };
128}
129/**
130 * Essential assertions before executing to provide developer feedback for
131 * improper use of the GraphQL library.
132 *
133 * @internal
134 */
135
136
137export function assertValidExecutionArguments(schema, document, rawVariableValues) {
138 document || devAssert(0, 'Must provide document.'); // If the schema used for execution is invalid, throw an error.
139
140 assertValidSchema(schema); // Variables, if provided, must be an object.
141
142 rawVariableValues == null || isObjectLike(rawVariableValues) || devAssert(0, 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.');
143}
144/**
145 * Constructs a ExecutionContext object from the arguments passed to
146 * execute, which we will pass throughout the other execution methods.
147 *
148 * Throws a GraphQLError if a valid execution context cannot be created.
149 *
150 * @internal
151 */
152
153export function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver, typeResolver) {
154 var _definition$name, _operation$variableDe;
155
156 var operation;
157 var fragments = Object.create(null);
158
159 for (var _i2 = 0, _document$definitions2 = document.definitions; _i2 < _document$definitions2.length; _i2++) {
160 var definition = _document$definitions2[_i2];
161
162 switch (definition.kind) {
163 case Kind.OPERATION_DEFINITION:
164 if (operationName == null) {
165 if (operation !== undefined) {
166 return [new GraphQLError('Must provide operation name if query contains multiple operations.')];
167 }
168
169 operation = definition;
170 } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) {
171 operation = definition;
172 }
173
174 break;
175
176 case Kind.FRAGMENT_DEFINITION:
177 fragments[definition.name.value] = definition;
178 break;
179 }
180 }
181
182 if (!operation) {
183 if (operationName != null) {
184 return [new GraphQLError("Unknown operation named \"".concat(operationName, "\"."))];
185 }
186
187 return [new GraphQLError('Must provide an operation.')];
188 } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
189
190
191 var variableDefinitions = (_operation$variableDe = operation.variableDefinitions) !== null && _operation$variableDe !== void 0 ? _operation$variableDe : [];
192 var coercedVariableValues = getVariableValues(schema, variableDefinitions, rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {}, {
193 maxErrors: 50
194 });
195
196 if (coercedVariableValues.errors) {
197 return coercedVariableValues.errors;
198 }
199
200 return {
201 schema: schema,
202 fragments: fragments,
203 rootValue: rootValue,
204 contextValue: contextValue,
205 operation: operation,
206 variableValues: coercedVariableValues.coerced,
207 fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver,
208 typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver,
209 errors: []
210 };
211}
212/**
213 * Implements the "Evaluating operations" section of the spec.
214 */
215
216function executeOperation(exeContext, operation, rootValue) {
217 var type = getOperationRootType(exeContext.schema, operation);
218 var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null));
219 var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level,
220 // at which point we still log the error and null the parent field, which
221 // in this case is the entire response.
222
223 try {
224 var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields);
225
226 if (isPromise(result)) {
227 return result.then(undefined, function (error) {
228 exeContext.errors.push(error);
229 return Promise.resolve(null);
230 });
231 }
232
233 return result;
234 } catch (error) {
235 exeContext.errors.push(error);
236 return null;
237 }
238}
239/**
240 * Implements the "Evaluating selection sets" section of the spec
241 * for "write" mode.
242 */
243
244
245function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) {
246 return promiseReduce(Object.keys(fields), function (results, responseName) {
247 var fieldNodes = fields[responseName];
248 var fieldPath = addPath(path, responseName, parentType.name);
249 var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
250
251 if (result === undefined) {
252 return results;
253 }
254
255 if (isPromise(result)) {
256 return result.then(function (resolvedResult) {
257 results[responseName] = resolvedResult;
258 return results;
259 });
260 }
261
262 results[responseName] = result;
263 return results;
264 }, Object.create(null));
265}
266/**
267 * Implements the "Evaluating selection sets" section of the spec
268 * for "read" mode.
269 */
270
271
272function executeFields(exeContext, parentType, sourceValue, path, fields) {
273 var results = Object.create(null);
274 var containsPromise = false;
275
276 for (var _i4 = 0, _Object$keys2 = Object.keys(fields); _i4 < _Object$keys2.length; _i4++) {
277 var responseName = _Object$keys2[_i4];
278 var fieldNodes = fields[responseName];
279 var fieldPath = addPath(path, responseName, parentType.name);
280 var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
281
282 if (result !== undefined) {
283 results[responseName] = result;
284
285 if (isPromise(result)) {
286 containsPromise = true;
287 }
288 }
289 } // If there are no promises, we can just return the object
290
291
292 if (!containsPromise) {
293 return results;
294 } // Otherwise, results is a map from field name to the result of resolving that
295 // field, which is possibly a promise. Return a promise that will return this
296 // same map, but with any promises replaced with the values they resolved to.
297
298
299 return promiseForObject(results);
300}
301/**
302 * Given a selectionSet, adds all of the fields in that selection to
303 * the passed in map of fields, and returns it at the end.
304 *
305 * CollectFields requires the "runtime type" of an object. For a field which
306 * returns an Interface or Union type, the "runtime type" will be the actual
307 * Object type returned by that field.
308 *
309 * @internal
310 */
311
312
313export function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {
314 for (var _i6 = 0, _selectionSet$selecti2 = selectionSet.selections; _i6 < _selectionSet$selecti2.length; _i6++) {
315 var selection = _selectionSet$selecti2[_i6];
316
317 switch (selection.kind) {
318 case Kind.FIELD:
319 {
320 if (!shouldIncludeNode(exeContext, selection)) {
321 continue;
322 }
323
324 var name = getFieldEntryKey(selection);
325
326 if (!fields[name]) {
327 fields[name] = [];
328 }
329
330 fields[name].push(selection);
331 break;
332 }
333
334 case Kind.INLINE_FRAGMENT:
335 {
336 if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) {
337 continue;
338 }
339
340 collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);
341 break;
342 }
343
344 case Kind.FRAGMENT_SPREAD:
345 {
346 var fragName = selection.name.value;
347
348 if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) {
349 continue;
350 }
351
352 visitedFragmentNames[fragName] = true;
353 var fragment = exeContext.fragments[fragName];
354
355 if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) {
356 continue;
357 }
358
359 collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);
360 break;
361 }
362 }
363 }
364
365 return fields;
366}
367/**
368 * Determines if a field should be included based on the @include and @skip
369 * directives, where @skip has higher precedence than @include.
370 */
371
372function shouldIncludeNode(exeContext, node) {
373 var skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues);
374
375 if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) {
376 return false;
377 }
378
379 var include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues);
380
381 if ((include === null || include === void 0 ? void 0 : include.if) === false) {
382 return false;
383 }
384
385 return true;
386}
387/**
388 * Determines if a fragment is applicable to the given type.
389 */
390
391
392function doesFragmentConditionMatch(exeContext, fragment, type) {
393 var typeConditionNode = fragment.typeCondition;
394
395 if (!typeConditionNode) {
396 return true;
397 }
398
399 var conditionalType = typeFromAST(exeContext.schema, typeConditionNode);
400
401 if (conditionalType === type) {
402 return true;
403 }
404
405 if (isAbstractType(conditionalType)) {
406 return exeContext.schema.isSubType(conditionalType, type);
407 }
408
409 return false;
410}
411/**
412 * Implements the logic to compute the key of a given field's entry
413 */
414
415
416function getFieldEntryKey(node) {
417 return node.alias ? node.alias.value : node.name.value;
418}
419/**
420 * Resolves the field on the given source object. In particular, this
421 * figures out the value that the field returns by calling its resolve function,
422 * then calls completeValue to complete promises, serialize scalars, or execute
423 * the sub-selection-set for objects.
424 */
425
426
427function resolveField(exeContext, parentType, source, fieldNodes, path) {
428 var _fieldDef$resolve;
429
430 var fieldNode = fieldNodes[0];
431 var fieldName = fieldNode.name.value;
432 var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName);
433
434 if (!fieldDef) {
435 return;
436 }
437
438 var returnType = fieldDef.type;
439 var resolveFn = (_fieldDef$resolve = fieldDef.resolve) !== null && _fieldDef$resolve !== void 0 ? _fieldDef$resolve : exeContext.fieldResolver;
440 var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal or abrupt (error).
441
442 try {
443 // Build a JS object of arguments from the field.arguments AST, using the
444 // variables scope to fulfill any variable references.
445 // TODO: find a way to memoize, in case this field is within a List type.
446 var args = getArgumentValues(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that
447 // is provided to every resolve function within an execution. It is commonly
448 // used to represent an authenticated user, or request-specific caches.
449
450 var _contextValue = exeContext.contextValue;
451 var result = resolveFn(source, args, _contextValue, info);
452 var completed;
453
454 if (isPromise(result)) {
455 completed = result.then(function (resolved) {
456 return completeValue(exeContext, returnType, fieldNodes, info, path, resolved);
457 });
458 } else {
459 completed = completeValue(exeContext, returnType, fieldNodes, info, path, result);
460 }
461
462 if (isPromise(completed)) {
463 // Note: we don't rely on a `catch` method, but we do expect "thenable"
464 // to take a second callback for the error case.
465 return completed.then(undefined, function (rawError) {
466 var error = locatedError(rawError, fieldNodes, pathToArray(path));
467 return handleFieldError(error, returnType, exeContext);
468 });
469 }
470
471 return completed;
472 } catch (rawError) {
473 var error = locatedError(rawError, fieldNodes, pathToArray(path));
474 return handleFieldError(error, returnType, exeContext);
475 }
476}
477/**
478 * @internal
479 */
480
481
482export function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) {
483 // The resolve function's optional fourth argument is a collection of
484 // information about the current execution state.
485 return {
486 fieldName: fieldDef.name,
487 fieldNodes: fieldNodes,
488 returnType: fieldDef.type,
489 parentType: parentType,
490 path: path,
491 schema: exeContext.schema,
492 fragments: exeContext.fragments,
493 rootValue: exeContext.rootValue,
494 operation: exeContext.operation,
495 variableValues: exeContext.variableValues
496 };
497}
498
499function handleFieldError(error, returnType, exeContext) {
500 // If the field type is non-nullable, then it is resolved without any
501 // protection from errors, however it still properly locates the error.
502 if (isNonNullType(returnType)) {
503 throw error;
504 } // Otherwise, error protection is applied, logging the error and resolving
505 // a null value for this field if one is encountered.
506
507
508 exeContext.errors.push(error);
509 return null;
510}
511/**
512 * Implements the instructions for completeValue as defined in the
513 * "Field entries" section of the spec.
514 *
515 * If the field type is Non-Null, then this recursively completes the value
516 * for the inner type. It throws a field error if that completion returns null,
517 * as per the "Nullability" section of the spec.
518 *
519 * If the field type is a List, then this recursively completes the value
520 * for the inner type on each item in the list.
521 *
522 * If the field type is a Scalar or Enum, ensures the completed value is a legal
523 * value of the type by calling the `serialize` method of GraphQL type
524 * definition.
525 *
526 * If the field is an abstract type, determine the runtime type of the value
527 * and then complete based on that type
528 *
529 * Otherwise, the field type expects a sub-selection set, and will complete the
530 * value by evaluating all sub-selections.
531 */
532
533
534function completeValue(exeContext, returnType, fieldNodes, info, path, result) {
535 // If result is an Error, throw a located error.
536 if (result instanceof Error) {
537 throw result;
538 } // If field type is NonNull, complete for inner type, and throw field error
539 // if result is null.
540
541
542 if (isNonNullType(returnType)) {
543 var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result);
544
545 if (completed === null) {
546 throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, "."));
547 }
548
549 return completed;
550 } // If result value is null or undefined then return null.
551
552
553 if (result == null) {
554 return null;
555 } // If field type is List, complete each item in the list with the inner type
556
557
558 if (isListType(returnType)) {
559 return completeListValue(exeContext, returnType, fieldNodes, info, path, result);
560 } // If field type is a leaf type, Scalar or Enum, serialize to a valid value,
561 // returning null if serialization is not possible.
562
563
564 if (isLeafType(returnType)) {
565 return completeLeafValue(returnType, result);
566 } // If field type is an abstract type, Interface or Union, determine the
567 // runtime Object type and complete for that type.
568
569
570 if (isAbstractType(returnType)) {
571 return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result);
572 } // If field type is Object, execute and complete all sub-selections.
573 // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')
574
575
576 if (isObjectType(returnType)) {
577 return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result);
578 } // istanbul ignore next (Not reachable. All possible output types have been considered)
579
580
581 false || invariant(0, 'Cannot complete value of unexpected output type: ' + inspect(returnType));
582}
583/**
584 * Complete a list value by completing each item in the list with the
585 * inner type
586 */
587
588
589function completeListValue(exeContext, returnType, fieldNodes, info, path, result) {
590 // This is specified as a simple map, however we're optimizing the path
591 // where the list contains no Promises by avoiding creating another Promise.
592 var itemType = returnType.ofType;
593 var containsPromise = false;
594 var completedResults = safeArrayFrom(result, function (item, index) {
595 // No need to modify the info object containing the path,
596 // since from here on it is not ever accessed by resolver functions.
597 var itemPath = addPath(path, index, undefined);
598
599 try {
600 var completedItem;
601
602 if (isPromise(item)) {
603 completedItem = item.then(function (resolved) {
604 return completeValue(exeContext, itemType, fieldNodes, info, itemPath, resolved);
605 });
606 } else {
607 completedItem = completeValue(exeContext, itemType, fieldNodes, info, itemPath, item);
608 }
609
610 if (isPromise(completedItem)) {
611 containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable"
612 // to take a second callback for the error case.
613
614 return completedItem.then(undefined, function (rawError) {
615 var error = locatedError(rawError, fieldNodes, pathToArray(itemPath));
616 return handleFieldError(error, itemType, exeContext);
617 });
618 }
619
620 return completedItem;
621 } catch (rawError) {
622 var error = locatedError(rawError, fieldNodes, pathToArray(itemPath));
623 return handleFieldError(error, itemType, exeContext);
624 }
625 });
626
627 if (completedResults == null) {
628 throw new GraphQLError("Expected Iterable, but did not find one for field \"".concat(info.parentType.name, ".").concat(info.fieldName, "\"."));
629 }
630
631 return containsPromise ? Promise.all(completedResults) : completedResults;
632}
633/**
634 * Complete a Scalar or Enum by serializing to a valid value, returning
635 * null if serialization is not possible.
636 */
637
638
639function completeLeafValue(returnType, result) {
640 var serializedResult = returnType.serialize(result);
641
642 if (serializedResult === undefined) {
643 throw new Error("Expected a value of type \"".concat(inspect(returnType), "\" but ") + "received: ".concat(inspect(result)));
644 }
645
646 return serializedResult;
647}
648/**
649 * Complete a value of an abstract type by determining the runtime object type
650 * of that value, then complete the value for that type.
651 */
652
653
654function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) {
655 var _returnType$resolveTy;
656
657 var resolveTypeFn = (_returnType$resolveTy = returnType.resolveType) !== null && _returnType$resolveTy !== void 0 ? _returnType$resolveTy : exeContext.typeResolver;
658 var contextValue = exeContext.contextValue;
659 var runtimeType = resolveTypeFn(result, contextValue, info, returnType);
660
661 if (isPromise(runtimeType)) {
662 return runtimeType.then(function (resolvedRuntimeType) {
663 return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
664 });
665 }
666
667 return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
668}
669
670function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) {
671 if (runtimeTypeOrName == null) {
672 throw new GraphQLError("Abstract type \"".concat(returnType.name, "\" must resolve to an Object type at runtime for field \"").concat(info.parentType.name, ".").concat(info.fieldName, "\". Either the \"").concat(returnType.name, "\" type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function."), fieldNodes);
673 } // FIXME: temporary workaround until support for passing object types would be removed in v16.0.0
674
675
676 var runtimeTypeName = isNamedType(runtimeTypeOrName) ? runtimeTypeOrName.name : runtimeTypeOrName;
677
678 if (typeof runtimeTypeName !== 'string') {
679 throw new GraphQLError("Abstract type \"".concat(returnType.name, "\" must resolve to an Object type at runtime for field \"").concat(info.parentType.name, ".").concat(info.fieldName, "\" with ") + "value ".concat(inspect(result), ", received \"").concat(inspect(runtimeTypeOrName), "\"."));
680 }
681
682 var runtimeType = exeContext.schema.getType(runtimeTypeName);
683
684 if (runtimeType == null) {
685 throw new GraphQLError("Abstract type \"".concat(returnType.name, "\" was resolve to a type \"").concat(runtimeTypeName, "\" that does not exist inside schema."), fieldNodes);
686 }
687
688 if (!isObjectType(runtimeType)) {
689 throw new GraphQLError("Abstract type \"".concat(returnType.name, "\" was resolve to a non-object type \"").concat(runtimeTypeName, "\"."), fieldNodes);
690 }
691
692 if (!exeContext.schema.isSubType(returnType, runtimeType)) {
693 throw new GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type for \"").concat(returnType.name, "\"."), fieldNodes);
694 }
695
696 return runtimeType;
697}
698/**
699 * Complete an Object value by executing all sub-selections.
700 */
701
702
703function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) {
704 // If there is an isTypeOf predicate function, call it with the
705 // current result. If isTypeOf returns false, then raise an error rather
706 // than continuing execution.
707 if (returnType.isTypeOf) {
708 var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);
709
710 if (isPromise(isTypeOf)) {
711 return isTypeOf.then(function (resolvedIsTypeOf) {
712 if (!resolvedIsTypeOf) {
713 throw invalidReturnTypeError(returnType, result, fieldNodes);
714 }
715
716 return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);
717 });
718 }
719
720 if (!isTypeOf) {
721 throw invalidReturnTypeError(returnType, result, fieldNodes);
722 }
723 }
724
725 return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);
726}
727
728function invalidReturnTypeError(returnType, result, fieldNodes) {
729 return new GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat(inspect(result), "."), fieldNodes);
730}
731
732function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) {
733 // Collect sub-fields to execute to complete this value.
734 var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);
735 return executeFields(exeContext, returnType, result, path, subFieldNodes);
736}
737/**
738 * A memoized collection of relevant subfields with regard to the return
739 * type. Memoizing ensures the subfields are not repeatedly calculated, which
740 * saves overhead when resolving lists of values.
741 */
742
743
744var collectSubfields = memoize3(_collectSubfields);
745
746function _collectSubfields(exeContext, returnType, fieldNodes) {
747 var subFieldNodes = Object.create(null);
748 var visitedFragmentNames = Object.create(null);
749
750 for (var _i8 = 0; _i8 < fieldNodes.length; _i8++) {
751 var node = fieldNodes[_i8];
752
753 if (node.selectionSet) {
754 subFieldNodes = collectFields(exeContext, returnType, node.selectionSet, subFieldNodes, visitedFragmentNames);
755 }
756 }
757
758 return subFieldNodes;
759}
760/**
761 * If a resolveType function is not given, then a default resolve behavior is
762 * used which attempts two strategies:
763 *
764 * First, See if the provided value has a `__typename` field defined, if so, use
765 * that value as name of the resolved type.
766 *
767 * Otherwise, test each possible type for the abstract type by calling
768 * isTypeOf for the object being coerced, returning the first type that matches.
769 */
770
771
772export var defaultTypeResolver = function defaultTypeResolver(value, contextValue, info, abstractType) {
773 // First, look for `__typename`.
774 if (isObjectLike(value) && typeof value.__typename === 'string') {
775 return value.__typename;
776 } // Otherwise, test each possible type.
777
778
779 var possibleTypes = info.schema.getPossibleTypes(abstractType);
780 var promisedIsTypeOfResults = [];
781
782 for (var i = 0; i < possibleTypes.length; i++) {
783 var type = possibleTypes[i];
784
785 if (type.isTypeOf) {
786 var isTypeOfResult = type.isTypeOf(value, contextValue, info);
787
788 if (isPromise(isTypeOfResult)) {
789 promisedIsTypeOfResults[i] = isTypeOfResult;
790 } else if (isTypeOfResult) {
791 return type.name;
792 }
793 }
794 }
795
796 if (promisedIsTypeOfResults.length) {
797 return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) {
798 for (var _i9 = 0; _i9 < isTypeOfResults.length; _i9++) {
799 if (isTypeOfResults[_i9]) {
800 return possibleTypes[_i9].name;
801 }
802 }
803 });
804 }
805};
806/**
807 * If a resolve function is not given, then a default resolve behavior is used
808 * which takes the property of the source object of the same name as the field
809 * and returns it as the result, or if it's a function, returns the result
810 * of calling that function while passing along args and context value.
811 */
812
813export var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) {
814 // ensure source is a value for which property access is acceptable.
815 if (isObjectLike(source) || typeof source === 'function') {
816 var property = source[info.fieldName];
817
818 if (typeof property === 'function') {
819 return source[info.fieldName](args, contextValue, info);
820 }
821
822 return property;
823 }
824};
825/**
826 * This method looks up the field on the given type definition.
827 * It has special casing for the three introspection fields,
828 * __schema, __type and __typename. __typename is special because
829 * it can always be queried as a field, even in situations where no
830 * other fields are allowed, like on a Union. __schema and __type
831 * could get automatically added to the query type, but that would
832 * require mutating type definitions, which would cause issues.
833 *
834 * @internal
835 */
836
837export function getFieldDef(schema, parentType, fieldName) {
838 if (fieldName === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
839 return SchemaMetaFieldDef;
840 } else if (fieldName === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
841 return TypeMetaFieldDef;
842 } else if (fieldName === TypeNameMetaFieldDef.name) {
843 return TypeNameMetaFieldDef;
844 }
845
846 return parentType.getFields()[fieldName];
847}