execute.mjs 30 KB

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