execute.js.flow 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. // @flow strict
  2. import type { Path } from '../jsutils/Path';
  3. import type { ObjMap } from '../jsutils/ObjMap';
  4. import type { PromiseOrValue } from '../jsutils/PromiseOrValue';
  5. import inspect from '../jsutils/inspect';
  6. import memoize3 from '../jsutils/memoize3';
  7. import invariant from '../jsutils/invariant';
  8. import devAssert from '../jsutils/devAssert';
  9. import isPromise from '../jsutils/isPromise';
  10. import isObjectLike from '../jsutils/isObjectLike';
  11. import safeArrayFrom from '../jsutils/safeArrayFrom';
  12. import promiseReduce from '../jsutils/promiseReduce';
  13. import promiseForObject from '../jsutils/promiseForObject';
  14. import { addPath, pathToArray } from '../jsutils/Path';
  15. import type { GraphQLFormattedError } from '../error/formatError';
  16. import { GraphQLError } from '../error/GraphQLError';
  17. import { locatedError } from '../error/locatedError';
  18. import type {
  19. DocumentNode,
  20. OperationDefinitionNode,
  21. SelectionSetNode,
  22. FieldNode,
  23. FragmentSpreadNode,
  24. InlineFragmentNode,
  25. FragmentDefinitionNode,
  26. } from '../language/ast';
  27. import { Kind } from '../language/kinds';
  28. import type { GraphQLSchema } from '../type/schema';
  29. import type {
  30. GraphQLObjectType,
  31. GraphQLOutputType,
  32. GraphQLLeafType,
  33. GraphQLAbstractType,
  34. GraphQLField,
  35. GraphQLFieldResolver,
  36. GraphQLResolveInfo,
  37. GraphQLTypeResolver,
  38. GraphQLList,
  39. } from '../type/definition';
  40. import { assertValidSchema } from '../type/validate';
  41. import {
  42. SchemaMetaFieldDef,
  43. TypeMetaFieldDef,
  44. TypeNameMetaFieldDef,
  45. } from '../type/introspection';
  46. import {
  47. GraphQLIncludeDirective,
  48. GraphQLSkipDirective,
  49. } from '../type/directives';
  50. import {
  51. isNamedType,
  52. isObjectType,
  53. isAbstractType,
  54. isLeafType,
  55. isListType,
  56. isNonNullType,
  57. } from '../type/definition';
  58. import { typeFromAST } from '../utilities/typeFromAST';
  59. import { getOperationRootType } from '../utilities/getOperationRootType';
  60. import {
  61. getVariableValues,
  62. getArgumentValues,
  63. getDirectiveValues,
  64. } from './values';
  65. /**
  66. * Terminology
  67. *
  68. * "Definitions" are the generic name for top-level statements in the document.
  69. * Examples of this include:
  70. * 1) Operations (such as a query)
  71. * 2) Fragments
  72. *
  73. * "Operations" are a generic name for requests in the document.
  74. * Examples of this include:
  75. * 1) query,
  76. * 2) mutation
  77. *
  78. * "Selections" are the definitions that can appear legally and at
  79. * single level of the query. These include:
  80. * 1) field references e.g "a"
  81. * 2) fragment "spreads" e.g. "...c"
  82. * 3) inline fragment "spreads" e.g. "...on Type { a }"
  83. */
  84. /**
  85. * Data that must be available at all points during query execution.
  86. *
  87. * Namely, schema of the type system that is currently executing,
  88. * and the fragments defined in the query document
  89. */
  90. export type ExecutionContext = {|
  91. schema: GraphQLSchema,
  92. fragments: ObjMap<FragmentDefinitionNode>,
  93. rootValue: mixed,
  94. contextValue: mixed,
  95. operation: OperationDefinitionNode,
  96. variableValues: { [variable: string]: mixed, ... },
  97. fieldResolver: GraphQLFieldResolver<any, any>,
  98. typeResolver: GraphQLTypeResolver<any, any>,
  99. errors: Array<GraphQLError>,
  100. |};
  101. /**
  102. * The result of GraphQL execution.
  103. *
  104. * - `errors` is included when any errors occurred as a non-empty array.
  105. * - `data` is the result of a successful execution of the query.
  106. * - `extensions` is reserved for adding non-standard properties.
  107. */
  108. export type ExecutionResult = {|
  109. errors?: $ReadOnlyArray<GraphQLError>,
  110. data?: ObjMap<mixed> | null,
  111. extensions?: ObjMap<mixed>,
  112. |};
  113. export type FormattedExecutionResult = {|
  114. errors?: $ReadOnlyArray<GraphQLFormattedError>,
  115. data?: ObjMap<mixed> | null,
  116. extensions?: ObjMap<mixed>,
  117. |};
  118. export type ExecutionArgs = {|
  119. schema: GraphQLSchema,
  120. document: DocumentNode,
  121. rootValue?: mixed,
  122. contextValue?: mixed,
  123. variableValues?: ?{ +[variable: string]: mixed, ... },
  124. operationName?: ?string,
  125. fieldResolver?: ?GraphQLFieldResolver<any, any>,
  126. typeResolver?: ?GraphQLTypeResolver<any, any>,
  127. |};
  128. /**
  129. * Implements the "Evaluating requests" section of the GraphQL specification.
  130. *
  131. * Returns either a synchronous ExecutionResult (if all encountered resolvers
  132. * are synchronous), or a Promise of an ExecutionResult that will eventually be
  133. * resolved and never rejected.
  134. *
  135. * If the arguments to this function do not result in a legal execution context,
  136. * a GraphQLError will be thrown immediately explaining the invalid input.
  137. *
  138. * Accepts either an object with named arguments, or individual arguments.
  139. */
  140. declare function execute(
  141. ExecutionArgs,
  142. ..._: []
  143. ): PromiseOrValue<ExecutionResult>;
  144. /* eslint-disable no-redeclare */
  145. declare function execute(
  146. schema: GraphQLSchema,
  147. document: DocumentNode,
  148. rootValue?: mixed,
  149. contextValue?: mixed,
  150. variableValues?: ?{ +[variable: string]: mixed, ... },
  151. operationName?: ?string,
  152. fieldResolver?: ?GraphQLFieldResolver<any, any>,
  153. typeResolver?: ?GraphQLTypeResolver<any, any>,
  154. ): PromiseOrValue<ExecutionResult>;
  155. export function execute(
  156. argsOrSchema,
  157. document,
  158. rootValue,
  159. contextValue,
  160. variableValues,
  161. operationName,
  162. fieldResolver,
  163. typeResolver,
  164. ) {
  165. /* eslint-enable no-redeclare */
  166. // Extract arguments from object args if provided.
  167. return arguments.length === 1
  168. ? executeImpl(argsOrSchema)
  169. : executeImpl({
  170. schema: argsOrSchema,
  171. document,
  172. rootValue,
  173. contextValue,
  174. variableValues,
  175. operationName,
  176. fieldResolver,
  177. typeResolver,
  178. });
  179. }
  180. /**
  181. * Also implements the "Evaluating requests" section of the GraphQL specification.
  182. * However, it guarantees to complete synchronously (or throw an error) assuming
  183. * that all field resolvers are also synchronous.
  184. */
  185. export function executeSync(args: ExecutionArgs): ExecutionResult {
  186. const result = executeImpl(args);
  187. // Assert that the execution was synchronous.
  188. if (isPromise(result)) {
  189. throw new Error('GraphQL execution failed to complete synchronously.');
  190. }
  191. return result;
  192. }
  193. function executeImpl(args: ExecutionArgs): PromiseOrValue<ExecutionResult> {
  194. const {
  195. schema,
  196. document,
  197. rootValue,
  198. contextValue,
  199. variableValues,
  200. operationName,
  201. fieldResolver,
  202. typeResolver,
  203. } = args;
  204. // If arguments are missing or incorrect, throw an error.
  205. assertValidExecutionArguments(schema, document, variableValues);
  206. // If a valid execution context cannot be created due to incorrect arguments,
  207. // a "Response" with only errors is returned.
  208. const exeContext = buildExecutionContext(
  209. schema,
  210. document,
  211. rootValue,
  212. contextValue,
  213. variableValues,
  214. operationName,
  215. fieldResolver,
  216. typeResolver,
  217. );
  218. // Return early errors if execution context failed.
  219. if (Array.isArray(exeContext)) {
  220. return { errors: exeContext };
  221. }
  222. // Return a Promise that will eventually resolve to the data described by
  223. // The "Response" section of the GraphQL specification.
  224. //
  225. // If errors are encountered while executing a GraphQL field, only that
  226. // field and its descendants will be omitted, and sibling fields will still
  227. // be executed. An execution which encounters errors will still result in a
  228. // resolved Promise.
  229. const data = executeOperation(exeContext, exeContext.operation, rootValue);
  230. return buildResponse(exeContext, data);
  231. }
  232. /**
  233. * Given a completed execution context and data, build the { errors, data }
  234. * response defined by the "Response" section of the GraphQL specification.
  235. */
  236. function buildResponse(
  237. exeContext: ExecutionContext,
  238. data: PromiseOrValue<ObjMap<mixed> | null>,
  239. ): PromiseOrValue<ExecutionResult> {
  240. if (isPromise(data)) {
  241. return data.then((resolved) => buildResponse(exeContext, resolved));
  242. }
  243. return exeContext.errors.length === 0
  244. ? { data }
  245. : { errors: exeContext.errors, data };
  246. }
  247. /**
  248. * Essential assertions before executing to provide developer feedback for
  249. * improper use of the GraphQL library.
  250. *
  251. * @internal
  252. */
  253. export function assertValidExecutionArguments(
  254. schema: GraphQLSchema,
  255. document: DocumentNode,
  256. rawVariableValues: ?{ +[variable: string]: mixed, ... },
  257. ): void {
  258. devAssert(document, 'Must provide document.');
  259. // If the schema used for execution is invalid, throw an error.
  260. assertValidSchema(schema);
  261. // Variables, if provided, must be an object.
  262. devAssert(
  263. rawVariableValues == null || isObjectLike(rawVariableValues),
  264. '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.',
  265. );
  266. }
  267. /**
  268. * Constructs a ExecutionContext object from the arguments passed to
  269. * execute, which we will pass throughout the other execution methods.
  270. *
  271. * Throws a GraphQLError if a valid execution context cannot be created.
  272. *
  273. * @internal
  274. */
  275. export function buildExecutionContext(
  276. schema: GraphQLSchema,
  277. document: DocumentNode,
  278. rootValue: mixed,
  279. contextValue: mixed,
  280. rawVariableValues: ?{ +[variable: string]: mixed, ... },
  281. operationName: ?string,
  282. fieldResolver: ?GraphQLFieldResolver<mixed, mixed>,
  283. typeResolver?: ?GraphQLTypeResolver<mixed, mixed>,
  284. ): $ReadOnlyArray<GraphQLError> | ExecutionContext {
  285. let operation: OperationDefinitionNode | void;
  286. const fragments: ObjMap<FragmentDefinitionNode> = Object.create(null);
  287. for (const definition of document.definitions) {
  288. switch (definition.kind) {
  289. case Kind.OPERATION_DEFINITION:
  290. if (operationName == null) {
  291. if (operation !== undefined) {
  292. return [
  293. new GraphQLError(
  294. 'Must provide operation name if query contains multiple operations.',
  295. ),
  296. ];
  297. }
  298. operation = definition;
  299. } else if (definition.name?.value === operationName) {
  300. operation = definition;
  301. }
  302. break;
  303. case Kind.FRAGMENT_DEFINITION:
  304. fragments[definition.name.value] = definition;
  305. break;
  306. }
  307. }
  308. if (!operation) {
  309. if (operationName != null) {
  310. return [new GraphQLError(`Unknown operation named "${operationName}".`)];
  311. }
  312. return [new GraphQLError('Must provide an operation.')];
  313. }
  314. // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
  315. const variableDefinitions = operation.variableDefinitions ?? [];
  316. const coercedVariableValues = getVariableValues(
  317. schema,
  318. variableDefinitions,
  319. rawVariableValues ?? {},
  320. { maxErrors: 50 },
  321. );
  322. if (coercedVariableValues.errors) {
  323. return coercedVariableValues.errors;
  324. }
  325. return {
  326. schema,
  327. fragments,
  328. rootValue,
  329. contextValue,
  330. operation,
  331. variableValues: coercedVariableValues.coerced,
  332. fieldResolver: fieldResolver ?? defaultFieldResolver,
  333. typeResolver: typeResolver ?? defaultTypeResolver,
  334. errors: [],
  335. };
  336. }
  337. /**
  338. * Implements the "Evaluating operations" section of the spec.
  339. */
  340. function executeOperation(
  341. exeContext: ExecutionContext,
  342. operation: OperationDefinitionNode,
  343. rootValue: mixed,
  344. ): PromiseOrValue<ObjMap<mixed> | null> {
  345. const type = getOperationRootType(exeContext.schema, operation);
  346. const fields = collectFields(
  347. exeContext,
  348. type,
  349. operation.selectionSet,
  350. Object.create(null),
  351. Object.create(null),
  352. );
  353. const path = undefined;
  354. // Errors from sub-fields of a NonNull type may propagate to the top level,
  355. // at which point we still log the error and null the parent field, which
  356. // in this case is the entire response.
  357. try {
  358. const result =
  359. operation.operation === 'mutation'
  360. ? executeFieldsSerially(exeContext, type, rootValue, path, fields)
  361. : executeFields(exeContext, type, rootValue, path, fields);
  362. if (isPromise(result)) {
  363. return result.then(undefined, (error) => {
  364. exeContext.errors.push(error);
  365. return Promise.resolve(null);
  366. });
  367. }
  368. return result;
  369. } catch (error) {
  370. exeContext.errors.push(error);
  371. return null;
  372. }
  373. }
  374. /**
  375. * Implements the "Evaluating selection sets" section of the spec
  376. * for "write" mode.
  377. */
  378. function executeFieldsSerially(
  379. exeContext: ExecutionContext,
  380. parentType: GraphQLObjectType,
  381. sourceValue: mixed,
  382. path: Path | void,
  383. fields: ObjMap<Array<FieldNode>>,
  384. ): PromiseOrValue<ObjMap<mixed>> {
  385. return promiseReduce(
  386. Object.keys(fields),
  387. (results, responseName) => {
  388. const fieldNodes = fields[responseName];
  389. const fieldPath = addPath(path, responseName, parentType.name);
  390. const result = resolveField(
  391. exeContext,
  392. parentType,
  393. sourceValue,
  394. fieldNodes,
  395. fieldPath,
  396. );
  397. if (result === undefined) {
  398. return results;
  399. }
  400. if (isPromise(result)) {
  401. return result.then((resolvedResult) => {
  402. results[responseName] = resolvedResult;
  403. return results;
  404. });
  405. }
  406. results[responseName] = result;
  407. return results;
  408. },
  409. Object.create(null),
  410. );
  411. }
  412. /**
  413. * Implements the "Evaluating selection sets" section of the spec
  414. * for "read" mode.
  415. */
  416. function executeFields(
  417. exeContext: ExecutionContext,
  418. parentType: GraphQLObjectType,
  419. sourceValue: mixed,
  420. path: Path | void,
  421. fields: ObjMap<Array<FieldNode>>,
  422. ): PromiseOrValue<ObjMap<mixed>> {
  423. const results = Object.create(null);
  424. let containsPromise = false;
  425. for (const responseName of Object.keys(fields)) {
  426. const fieldNodes = fields[responseName];
  427. const fieldPath = addPath(path, responseName, parentType.name);
  428. const result = resolveField(
  429. exeContext,
  430. parentType,
  431. sourceValue,
  432. fieldNodes,
  433. fieldPath,
  434. );
  435. if (result !== undefined) {
  436. results[responseName] = result;
  437. if (isPromise(result)) {
  438. containsPromise = true;
  439. }
  440. }
  441. }
  442. // If there are no promises, we can just return the object
  443. if (!containsPromise) {
  444. return results;
  445. }
  446. // Otherwise, results is a map from field name to the result of resolving that
  447. // field, which is possibly a promise. Return a promise that will return this
  448. // same map, but with any promises replaced with the values they resolved to.
  449. return promiseForObject(results);
  450. }
  451. /**
  452. * Given a selectionSet, adds all of the fields in that selection to
  453. * the passed in map of fields, and returns it at the end.
  454. *
  455. * CollectFields requires the "runtime type" of an object. For a field which
  456. * returns an Interface or Union type, the "runtime type" will be the actual
  457. * Object type returned by that field.
  458. *
  459. * @internal
  460. */
  461. export function collectFields(
  462. exeContext: ExecutionContext,
  463. runtimeType: GraphQLObjectType,
  464. selectionSet: SelectionSetNode,
  465. fields: ObjMap<Array<FieldNode>>,
  466. visitedFragmentNames: ObjMap<boolean>,
  467. ): ObjMap<Array<FieldNode>> {
  468. for (const selection of selectionSet.selections) {
  469. switch (selection.kind) {
  470. case Kind.FIELD: {
  471. if (!shouldIncludeNode(exeContext, selection)) {
  472. continue;
  473. }
  474. const name = getFieldEntryKey(selection);
  475. if (!fields[name]) {
  476. fields[name] = [];
  477. }
  478. fields[name].push(selection);
  479. break;
  480. }
  481. case Kind.INLINE_FRAGMENT: {
  482. if (
  483. !shouldIncludeNode(exeContext, selection) ||
  484. !doesFragmentConditionMatch(exeContext, selection, runtimeType)
  485. ) {
  486. continue;
  487. }
  488. collectFields(
  489. exeContext,
  490. runtimeType,
  491. selection.selectionSet,
  492. fields,
  493. visitedFragmentNames,
  494. );
  495. break;
  496. }
  497. case Kind.FRAGMENT_SPREAD: {
  498. const fragName = selection.name.value;
  499. if (
  500. visitedFragmentNames[fragName] ||
  501. !shouldIncludeNode(exeContext, selection)
  502. ) {
  503. continue;
  504. }
  505. visitedFragmentNames[fragName] = true;
  506. const fragment = exeContext.fragments[fragName];
  507. if (
  508. !fragment ||
  509. !doesFragmentConditionMatch(exeContext, fragment, runtimeType)
  510. ) {
  511. continue;
  512. }
  513. collectFields(
  514. exeContext,
  515. runtimeType,
  516. fragment.selectionSet,
  517. fields,
  518. visitedFragmentNames,
  519. );
  520. break;
  521. }
  522. }
  523. }
  524. return fields;
  525. }
  526. /**
  527. * Determines if a field should be included based on the @include and @skip
  528. * directives, where @skip has higher precedence than @include.
  529. */
  530. function shouldIncludeNode(
  531. exeContext: ExecutionContext,
  532. node: FragmentSpreadNode | FieldNode | InlineFragmentNode,
  533. ): boolean {
  534. const skip = getDirectiveValues(
  535. GraphQLSkipDirective,
  536. node,
  537. exeContext.variableValues,
  538. );
  539. if (skip?.if === true) {
  540. return false;
  541. }
  542. const include = getDirectiveValues(
  543. GraphQLIncludeDirective,
  544. node,
  545. exeContext.variableValues,
  546. );
  547. if (include?.if === false) {
  548. return false;
  549. }
  550. return true;
  551. }
  552. /**
  553. * Determines if a fragment is applicable to the given type.
  554. */
  555. function doesFragmentConditionMatch(
  556. exeContext: ExecutionContext,
  557. fragment: FragmentDefinitionNode | InlineFragmentNode,
  558. type: GraphQLObjectType,
  559. ): boolean {
  560. const typeConditionNode = fragment.typeCondition;
  561. if (!typeConditionNode) {
  562. return true;
  563. }
  564. const conditionalType = typeFromAST(exeContext.schema, typeConditionNode);
  565. if (conditionalType === type) {
  566. return true;
  567. }
  568. if (isAbstractType(conditionalType)) {
  569. return exeContext.schema.isSubType(conditionalType, type);
  570. }
  571. return false;
  572. }
  573. /**
  574. * Implements the logic to compute the key of a given field's entry
  575. */
  576. function getFieldEntryKey(node: FieldNode): string {
  577. return node.alias ? node.alias.value : node.name.value;
  578. }
  579. /**
  580. * Resolves the field on the given source object. In particular, this
  581. * figures out the value that the field returns by calling its resolve function,
  582. * then calls completeValue to complete promises, serialize scalars, or execute
  583. * the sub-selection-set for objects.
  584. */
  585. function resolveField(
  586. exeContext: ExecutionContext,
  587. parentType: GraphQLObjectType,
  588. source: mixed,
  589. fieldNodes: $ReadOnlyArray<FieldNode>,
  590. path: Path,
  591. ): PromiseOrValue<mixed> {
  592. const fieldNode = fieldNodes[0];
  593. const fieldName = fieldNode.name.value;
  594. const fieldDef = getFieldDef(exeContext.schema, parentType, fieldName);
  595. if (!fieldDef) {
  596. return;
  597. }
  598. const returnType = fieldDef.type;
  599. const resolveFn = fieldDef.resolve ?? exeContext.fieldResolver;
  600. const info = buildResolveInfo(
  601. exeContext,
  602. fieldDef,
  603. fieldNodes,
  604. parentType,
  605. path,
  606. );
  607. // Get the resolve function, regardless of if its result is normal or abrupt (error).
  608. try {
  609. // Build a JS object of arguments from the field.arguments AST, using the
  610. // variables scope to fulfill any variable references.
  611. // TODO: find a way to memoize, in case this field is within a List type.
  612. const args = getArgumentValues(
  613. fieldDef,
  614. fieldNodes[0],
  615. exeContext.variableValues,
  616. );
  617. // The resolve function's optional third argument is a context value that
  618. // is provided to every resolve function within an execution. It is commonly
  619. // used to represent an authenticated user, or request-specific caches.
  620. const contextValue = exeContext.contextValue;
  621. const result = resolveFn(source, args, contextValue, info);
  622. let completed;
  623. if (isPromise(result)) {
  624. completed = result.then((resolved) =>
  625. completeValue(exeContext, returnType, fieldNodes, info, path, resolved),
  626. );
  627. } else {
  628. completed = completeValue(
  629. exeContext,
  630. returnType,
  631. fieldNodes,
  632. info,
  633. path,
  634. result,
  635. );
  636. }
  637. if (isPromise(completed)) {
  638. // Note: we don't rely on a `catch` method, but we do expect "thenable"
  639. // to take a second callback for the error case.
  640. return completed.then(undefined, (rawError) => {
  641. const error = locatedError(rawError, fieldNodes, pathToArray(path));
  642. return handleFieldError(error, returnType, exeContext);
  643. });
  644. }
  645. return completed;
  646. } catch (rawError) {
  647. const error = locatedError(rawError, fieldNodes, pathToArray(path));
  648. return handleFieldError(error, returnType, exeContext);
  649. }
  650. }
  651. /**
  652. * @internal
  653. */
  654. export function buildResolveInfo(
  655. exeContext: ExecutionContext,
  656. fieldDef: GraphQLField<mixed, mixed>,
  657. fieldNodes: $ReadOnlyArray<FieldNode>,
  658. parentType: GraphQLObjectType,
  659. path: Path,
  660. ): GraphQLResolveInfo {
  661. // The resolve function's optional fourth argument is a collection of
  662. // information about the current execution state.
  663. return {
  664. fieldName: fieldDef.name,
  665. fieldNodes,
  666. returnType: fieldDef.type,
  667. parentType,
  668. path,
  669. schema: exeContext.schema,
  670. fragments: exeContext.fragments,
  671. rootValue: exeContext.rootValue,
  672. operation: exeContext.operation,
  673. variableValues: exeContext.variableValues,
  674. };
  675. }
  676. function handleFieldError(
  677. error: GraphQLError,
  678. returnType: GraphQLOutputType,
  679. exeContext: ExecutionContext,
  680. ): null {
  681. // If the field type is non-nullable, then it is resolved without any
  682. // protection from errors, however it still properly locates the error.
  683. if (isNonNullType(returnType)) {
  684. throw error;
  685. }
  686. // Otherwise, error protection is applied, logging the error and resolving
  687. // a null value for this field if one is encountered.
  688. exeContext.errors.push(error);
  689. return null;
  690. }
  691. /**
  692. * Implements the instructions for completeValue as defined in the
  693. * "Field entries" section of the spec.
  694. *
  695. * If the field type is Non-Null, then this recursively completes the value
  696. * for the inner type. It throws a field error if that completion returns null,
  697. * as per the "Nullability" section of the spec.
  698. *
  699. * If the field type is a List, then this recursively completes the value
  700. * for the inner type on each item in the list.
  701. *
  702. * If the field type is a Scalar or Enum, ensures the completed value is a legal
  703. * value of the type by calling the `serialize` method of GraphQL type
  704. * definition.
  705. *
  706. * If the field is an abstract type, determine the runtime type of the value
  707. * and then complete based on that type
  708. *
  709. * Otherwise, the field type expects a sub-selection set, and will complete the
  710. * value by evaluating all sub-selections.
  711. */
  712. function completeValue(
  713. exeContext: ExecutionContext,
  714. returnType: GraphQLOutputType,
  715. fieldNodes: $ReadOnlyArray<FieldNode>,
  716. info: GraphQLResolveInfo,
  717. path: Path,
  718. result: mixed,
  719. ): PromiseOrValue<mixed> {
  720. // If result is an Error, throw a located error.
  721. if (result instanceof Error) {
  722. throw result;
  723. }
  724. // If field type is NonNull, complete for inner type, and throw field error
  725. // if result is null.
  726. if (isNonNullType(returnType)) {
  727. const completed = completeValue(
  728. exeContext,
  729. returnType.ofType,
  730. fieldNodes,
  731. info,
  732. path,
  733. result,
  734. );
  735. if (completed === null) {
  736. throw new Error(
  737. `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`,
  738. );
  739. }
  740. return completed;
  741. }
  742. // If result value is null or undefined then return null.
  743. if (result == null) {
  744. return null;
  745. }
  746. // If field type is List, complete each item in the list with the inner type
  747. if (isListType(returnType)) {
  748. return completeListValue(
  749. exeContext,
  750. returnType,
  751. fieldNodes,
  752. info,
  753. path,
  754. result,
  755. );
  756. }
  757. // If field type is a leaf type, Scalar or Enum, serialize to a valid value,
  758. // returning null if serialization is not possible.
  759. if (isLeafType(returnType)) {
  760. return completeLeafValue(returnType, result);
  761. }
  762. // If field type is an abstract type, Interface or Union, determine the
  763. // runtime Object type and complete for that type.
  764. if (isAbstractType(returnType)) {
  765. return completeAbstractValue(
  766. exeContext,
  767. returnType,
  768. fieldNodes,
  769. info,
  770. path,
  771. result,
  772. );
  773. }
  774. // If field type is Object, execute and complete all sub-selections.
  775. // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')
  776. if (isObjectType(returnType)) {
  777. return completeObjectValue(
  778. exeContext,
  779. returnType,
  780. fieldNodes,
  781. info,
  782. path,
  783. result,
  784. );
  785. }
  786. // istanbul ignore next (Not reachable. All possible output types have been considered)
  787. invariant(
  788. false,
  789. 'Cannot complete value of unexpected output type: ' +
  790. inspect((returnType: empty)),
  791. );
  792. }
  793. /**
  794. * Complete a list value by completing each item in the list with the
  795. * inner type
  796. */
  797. function completeListValue(
  798. exeContext: ExecutionContext,
  799. returnType: GraphQLList<GraphQLOutputType>,
  800. fieldNodes: $ReadOnlyArray<FieldNode>,
  801. info: GraphQLResolveInfo,
  802. path: Path,
  803. result: mixed,
  804. ): PromiseOrValue<$ReadOnlyArray<mixed>> {
  805. // This is specified as a simple map, however we're optimizing the path
  806. // where the list contains no Promises by avoiding creating another Promise.
  807. const itemType = returnType.ofType;
  808. let containsPromise = false;
  809. const completedResults = safeArrayFrom(result, (item, index) => {
  810. // No need to modify the info object containing the path,
  811. // since from here on it is not ever accessed by resolver functions.
  812. const itemPath = addPath(path, index, undefined);
  813. try {
  814. let completedItem;
  815. if (isPromise(item)) {
  816. completedItem = item.then((resolved) =>
  817. completeValue(
  818. exeContext,
  819. itemType,
  820. fieldNodes,
  821. info,
  822. itemPath,
  823. resolved,
  824. ),
  825. );
  826. } else {
  827. completedItem = completeValue(
  828. exeContext,
  829. itemType,
  830. fieldNodes,
  831. info,
  832. itemPath,
  833. item,
  834. );
  835. }
  836. if (isPromise(completedItem)) {
  837. containsPromise = true;
  838. // Note: we don't rely on a `catch` method, but we do expect "thenable"
  839. // to take a second callback for the error case.
  840. return completedItem.then(undefined, (rawError) => {
  841. const error = locatedError(
  842. rawError,
  843. fieldNodes,
  844. pathToArray(itemPath),
  845. );
  846. return handleFieldError(error, itemType, exeContext);
  847. });
  848. }
  849. return completedItem;
  850. } catch (rawError) {
  851. const error = locatedError(rawError, fieldNodes, pathToArray(itemPath));
  852. return handleFieldError(error, itemType, exeContext);
  853. }
  854. });
  855. if (completedResults == null) {
  856. throw new GraphQLError(
  857. `Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`,
  858. );
  859. }
  860. return containsPromise ? Promise.all(completedResults) : completedResults;
  861. }
  862. /**
  863. * Complete a Scalar or Enum by serializing to a valid value, returning
  864. * null if serialization is not possible.
  865. */
  866. function completeLeafValue(returnType: GraphQLLeafType, result: mixed): mixed {
  867. const serializedResult = returnType.serialize(result);
  868. if (serializedResult === undefined) {
  869. throw new Error(
  870. `Expected a value of type "${inspect(returnType)}" but ` +
  871. `received: ${inspect(result)}`,
  872. );
  873. }
  874. return serializedResult;
  875. }
  876. /**
  877. * Complete a value of an abstract type by determining the runtime object type
  878. * of that value, then complete the value for that type.
  879. */
  880. function completeAbstractValue(
  881. exeContext: ExecutionContext,
  882. returnType: GraphQLAbstractType,
  883. fieldNodes: $ReadOnlyArray<FieldNode>,
  884. info: GraphQLResolveInfo,
  885. path: Path,
  886. result: mixed,
  887. ): PromiseOrValue<ObjMap<mixed>> {
  888. const resolveTypeFn = returnType.resolveType ?? exeContext.typeResolver;
  889. const contextValue = exeContext.contextValue;
  890. const runtimeType = resolveTypeFn(result, contextValue, info, returnType);
  891. if (isPromise(runtimeType)) {
  892. return runtimeType.then((resolvedRuntimeType) =>
  893. completeObjectValue(
  894. exeContext,
  895. ensureValidRuntimeType(
  896. resolvedRuntimeType,
  897. exeContext,
  898. returnType,
  899. fieldNodes,
  900. info,
  901. result,
  902. ),
  903. fieldNodes,
  904. info,
  905. path,
  906. result,
  907. ),
  908. );
  909. }
  910. return completeObjectValue(
  911. exeContext,
  912. ensureValidRuntimeType(
  913. runtimeType,
  914. exeContext,
  915. returnType,
  916. fieldNodes,
  917. info,
  918. result,
  919. ),
  920. fieldNodes,
  921. info,
  922. path,
  923. result,
  924. );
  925. }
  926. function ensureValidRuntimeType(
  927. runtimeTypeOrName: mixed,
  928. exeContext: ExecutionContext,
  929. returnType: GraphQLAbstractType,
  930. fieldNodes: $ReadOnlyArray<FieldNode>,
  931. info: GraphQLResolveInfo,
  932. result: mixed,
  933. ): GraphQLObjectType {
  934. if (runtimeTypeOrName == null) {
  935. throw new GraphQLError(
  936. `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}". Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`,
  937. fieldNodes,
  938. );
  939. }
  940. // FIXME: temporary workaround until support for passing object types would be removed in v16.0.0
  941. const runtimeTypeName = isNamedType(runtimeTypeOrName)
  942. ? runtimeTypeOrName.name
  943. : runtimeTypeOrName;
  944. if (typeof runtimeTypeName !== 'string') {
  945. throw new GraphQLError(
  946. `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` +
  947. `value ${inspect(result)}, received "${inspect(runtimeTypeOrName)}".`,
  948. );
  949. }
  950. const runtimeType = exeContext.schema.getType(runtimeTypeName);
  951. if (runtimeType == null) {
  952. throw new GraphQLError(
  953. `Abstract type "${returnType.name}" was resolve to a type "${runtimeTypeName}" that does not exist inside schema.`,
  954. fieldNodes,
  955. );
  956. }
  957. if (!isObjectType(runtimeType)) {
  958. throw new GraphQLError(
  959. `Abstract type "${returnType.name}" was resolve to a non-object type "${runtimeTypeName}".`,
  960. fieldNodes,
  961. );
  962. }
  963. if (!exeContext.schema.isSubType(returnType, runtimeType)) {
  964. throw new GraphQLError(
  965. `Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`,
  966. fieldNodes,
  967. );
  968. }
  969. return runtimeType;
  970. }
  971. /**
  972. * Complete an Object value by executing all sub-selections.
  973. */
  974. function completeObjectValue(
  975. exeContext: ExecutionContext,
  976. returnType: GraphQLObjectType,
  977. fieldNodes: $ReadOnlyArray<FieldNode>,
  978. info: GraphQLResolveInfo,
  979. path: Path,
  980. result: mixed,
  981. ): PromiseOrValue<ObjMap<mixed>> {
  982. // If there is an isTypeOf predicate function, call it with the
  983. // current result. If isTypeOf returns false, then raise an error rather
  984. // than continuing execution.
  985. if (returnType.isTypeOf) {
  986. const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);
  987. if (isPromise(isTypeOf)) {
  988. return isTypeOf.then((resolvedIsTypeOf) => {
  989. if (!resolvedIsTypeOf) {
  990. throw invalidReturnTypeError(returnType, result, fieldNodes);
  991. }
  992. return collectAndExecuteSubfields(
  993. exeContext,
  994. returnType,
  995. fieldNodes,
  996. path,
  997. result,
  998. );
  999. });
  1000. }
  1001. if (!isTypeOf) {
  1002. throw invalidReturnTypeError(returnType, result, fieldNodes);
  1003. }
  1004. }
  1005. return collectAndExecuteSubfields(
  1006. exeContext,
  1007. returnType,
  1008. fieldNodes,
  1009. path,
  1010. result,
  1011. );
  1012. }
  1013. function invalidReturnTypeError(
  1014. returnType: GraphQLObjectType,
  1015. result: mixed,
  1016. fieldNodes: $ReadOnlyArray<FieldNode>,
  1017. ): GraphQLError {
  1018. return new GraphQLError(
  1019. `Expected value of type "${returnType.name}" but got: ${inspect(result)}.`,
  1020. fieldNodes,
  1021. );
  1022. }
  1023. function collectAndExecuteSubfields(
  1024. exeContext: ExecutionContext,
  1025. returnType: GraphQLObjectType,
  1026. fieldNodes: $ReadOnlyArray<FieldNode>,
  1027. path: Path,
  1028. result: mixed,
  1029. ): PromiseOrValue<ObjMap<mixed>> {
  1030. // Collect sub-fields to execute to complete this value.
  1031. const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);
  1032. return executeFields(exeContext, returnType, result, path, subFieldNodes);
  1033. }
  1034. /**
  1035. * A memoized collection of relevant subfields with regard to the return
  1036. * type. Memoizing ensures the subfields are not repeatedly calculated, which
  1037. * saves overhead when resolving lists of values.
  1038. */
  1039. const collectSubfields = memoize3(_collectSubfields);
  1040. function _collectSubfields(
  1041. exeContext: ExecutionContext,
  1042. returnType: GraphQLObjectType,
  1043. fieldNodes: $ReadOnlyArray<FieldNode>,
  1044. ): ObjMap<Array<FieldNode>> {
  1045. let subFieldNodes = Object.create(null);
  1046. const visitedFragmentNames = Object.create(null);
  1047. for (const node of fieldNodes) {
  1048. if (node.selectionSet) {
  1049. subFieldNodes = collectFields(
  1050. exeContext,
  1051. returnType,
  1052. node.selectionSet,
  1053. subFieldNodes,
  1054. visitedFragmentNames,
  1055. );
  1056. }
  1057. }
  1058. return subFieldNodes;
  1059. }
  1060. /**
  1061. * If a resolveType function is not given, then a default resolve behavior is
  1062. * used which attempts two strategies:
  1063. *
  1064. * First, See if the provided value has a `__typename` field defined, if so, use
  1065. * that value as name of the resolved type.
  1066. *
  1067. * Otherwise, test each possible type for the abstract type by calling
  1068. * isTypeOf for the object being coerced, returning the first type that matches.
  1069. */
  1070. export const defaultTypeResolver: GraphQLTypeResolver<mixed, mixed> = function (
  1071. value,
  1072. contextValue,
  1073. info,
  1074. abstractType,
  1075. ) {
  1076. // First, look for `__typename`.
  1077. if (isObjectLike(value) && typeof value.__typename === 'string') {
  1078. return value.__typename;
  1079. }
  1080. // Otherwise, test each possible type.
  1081. const possibleTypes = info.schema.getPossibleTypes(abstractType);
  1082. const promisedIsTypeOfResults = [];
  1083. for (let i = 0; i < possibleTypes.length; i++) {
  1084. const type = possibleTypes[i];
  1085. if (type.isTypeOf) {
  1086. const isTypeOfResult = type.isTypeOf(value, contextValue, info);
  1087. if (isPromise(isTypeOfResult)) {
  1088. promisedIsTypeOfResults[i] = isTypeOfResult;
  1089. } else if (isTypeOfResult) {
  1090. return type.name;
  1091. }
  1092. }
  1093. }
  1094. if (promisedIsTypeOfResults.length) {
  1095. return Promise.all(promisedIsTypeOfResults).then((isTypeOfResults) => {
  1096. for (let i = 0; i < isTypeOfResults.length; i++) {
  1097. if (isTypeOfResults[i]) {
  1098. return possibleTypes[i].name;
  1099. }
  1100. }
  1101. });
  1102. }
  1103. };
  1104. /**
  1105. * If a resolve function is not given, then a default resolve behavior is used
  1106. * which takes the property of the source object of the same name as the field
  1107. * and returns it as the result, or if it's a function, returns the result
  1108. * of calling that function while passing along args and context value.
  1109. */
  1110. export const defaultFieldResolver: GraphQLFieldResolver<
  1111. mixed,
  1112. mixed,
  1113. > = function (source: any, args, contextValue, info) {
  1114. // ensure source is a value for which property access is acceptable.
  1115. if (isObjectLike(source) || typeof source === 'function') {
  1116. const property = source[info.fieldName];
  1117. if (typeof property === 'function') {
  1118. return source[info.fieldName](args, contextValue, info);
  1119. }
  1120. return property;
  1121. }
  1122. };
  1123. /**
  1124. * This method looks up the field on the given type definition.
  1125. * It has special casing for the three introspection fields,
  1126. * __schema, __type and __typename. __typename is special because
  1127. * it can always be queried as a field, even in situations where no
  1128. * other fields are allowed, like on a Union. __schema and __type
  1129. * could get automatically added to the query type, but that would
  1130. * require mutating type definitions, which would cause issues.
  1131. *
  1132. * @internal
  1133. */
  1134. export function getFieldDef(
  1135. schema: GraphQLSchema,
  1136. parentType: GraphQLObjectType,
  1137. fieldName: string,
  1138. ): ?GraphQLField<mixed, mixed> {
  1139. if (
  1140. fieldName === SchemaMetaFieldDef.name &&
  1141. schema.getQueryType() === parentType
  1142. ) {
  1143. return SchemaMetaFieldDef;
  1144. } else if (
  1145. fieldName === TypeMetaFieldDef.name &&
  1146. schema.getQueryType() === parentType
  1147. ) {
  1148. return TypeMetaFieldDef;
  1149. } else if (fieldName === TypeNameMetaFieldDef.name) {
  1150. return TypeNameMetaFieldDef;
  1151. }
  1152. return parentType.getFields()[fieldName];
  1153. }