execute.mjs 28 KB

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