UNPKG

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