UNPKG

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