execute.js 29 KB

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