execute.js 31 KB

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