execute.js.flow 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. // @flow strict
  2. import arrayFrom from '../polyfills/arrayFrom';
  3. import type { Path } from '../jsutils/Path';
  4. import type { ObjMap } from '../jsutils/ObjMap';
  5. import type { PromiseOrValue } from '../jsutils/PromiseOrValue';
  6. import inspect from '../jsutils/inspect';
  7. import memoize3 from '../jsutils/memoize3';
  8. import invariant from '../jsutils/invariant';
  9. import devAssert from '../jsutils/devAssert';
  10. import isPromise from '../jsutils/isPromise';
  11. import isObjectLike from '../jsutils/isObjectLike';
  12. import isCollection from '../jsutils/isCollection';
  13. import promiseReduce from '../jsutils/promiseReduce';
  14. import promiseForObject from '../jsutils/promiseForObject';
  15. import { addPath, pathToArray } from '../jsutils/Path';
  16. import type { GraphQLFormattedError } from '../error/formatError';
  17. import { GraphQLError } from '../error/GraphQLError';
  18. import { locatedError } from '../error/locatedError';
  19. import type {
  20. DocumentNode,
  21. OperationDefinitionNode,
  22. SelectionSetNode,
  23. FieldNode,
  24. FragmentSpreadNode,
  25. InlineFragmentNode,
  26. FragmentDefinitionNode,
  27. } from '../language/ast';
  28. import { Kind } from '../language/kinds';
  29. import type { GraphQLSchema } from '../type/schema';
  30. import type {
  31. GraphQLObjectType,
  32. GraphQLOutputType,
  33. GraphQLLeafType,
  34. GraphQLAbstractType,
  35. GraphQLField,
  36. GraphQLFieldResolver,
  37. GraphQLResolveInfo,
  38. GraphQLTypeResolver,
  39. GraphQLList,
  40. } from '../type/definition';
  41. import { assertValidSchema } from '../type/validate';
  42. import {
  43. SchemaMetaFieldDef,
  44. TypeMetaFieldDef,
  45. TypeNameMetaFieldDef,
  46. } from '../type/introspection';
  47. import {
  48. GraphQLIncludeDirective,
  49. GraphQLSkipDirective,
  50. } from '../type/directives';
  51. import {
  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. //
  358. // Similar to completeValueCatchingError.
  359. try {
  360. const result =
  361. operation.operation === 'mutation'
  362. ? executeFieldsSerially(exeContext, type, rootValue, path, fields)
  363. : executeFields(exeContext, type, rootValue, path, fields);
  364. if (isPromise(result)) {
  365. return result.then(undefined, (error) => {
  366. exeContext.errors.push(error);
  367. return Promise.resolve(null);
  368. });
  369. }
  370. return result;
  371. } catch (error) {
  372. exeContext.errors.push(error);
  373. return null;
  374. }
  375. }
  376. /**
  377. * Implements the "Evaluating selection sets" section of the spec
  378. * for "write" mode.
  379. */
  380. function executeFieldsSerially(
  381. exeContext: ExecutionContext,
  382. parentType: GraphQLObjectType,
  383. sourceValue: mixed,
  384. path: Path | void,
  385. fields: ObjMap<Array<FieldNode>>,
  386. ): PromiseOrValue<ObjMap<mixed>> {
  387. return promiseReduce(
  388. Object.keys(fields),
  389. (results, responseName) => {
  390. const fieldNodes = fields[responseName];
  391. const fieldPath = addPath(path, responseName, parentType.name);
  392. const result = resolveField(
  393. exeContext,
  394. parentType,
  395. sourceValue,
  396. fieldNodes,
  397. fieldPath,
  398. );
  399. if (result === undefined) {
  400. return results;
  401. }
  402. if (isPromise(result)) {
  403. return result.then((resolvedResult) => {
  404. results[responseName] = resolvedResult;
  405. return results;
  406. });
  407. }
  408. results[responseName] = result;
  409. return results;
  410. },
  411. Object.create(null),
  412. );
  413. }
  414. /**
  415. * Implements the "Evaluating selection sets" section of the spec
  416. * for "read" mode.
  417. */
  418. function executeFields(
  419. exeContext: ExecutionContext,
  420. parentType: GraphQLObjectType,
  421. sourceValue: mixed,
  422. path: Path | void,
  423. fields: ObjMap<Array<FieldNode>>,
  424. ): PromiseOrValue<ObjMap<mixed>> {
  425. const results = Object.create(null);
  426. let containsPromise = false;
  427. for (const responseName of Object.keys(fields)) {
  428. const fieldNodes = fields[responseName];
  429. const fieldPath = addPath(path, responseName, parentType.name);
  430. const result = resolveField(
  431. exeContext,
  432. parentType,
  433. sourceValue,
  434. fieldNodes,
  435. fieldPath,
  436. );
  437. if (result !== undefined) {
  438. results[responseName] = result;
  439. if (!containsPromise && isPromise(result)) {
  440. containsPromise = true;
  441. }
  442. }
  443. }
  444. // If there are no promises, we can just return the object
  445. if (!containsPromise) {
  446. return results;
  447. }
  448. // Otherwise, results is a map from field name to the result of resolving that
  449. // field, which is possibly a promise. Return a promise that will return this
  450. // same map, but with any promises replaced with the values they resolved to.
  451. return promiseForObject(results);
  452. }
  453. /**
  454. * Given a selectionSet, adds all of the fields in that selection to
  455. * the passed in map of fields, and returns it at the end.
  456. *
  457. * CollectFields requires the "runtime type" of an object. For a field which
  458. * returns an Interface or Union type, the "runtime type" will be the actual
  459. * Object type returned by that field.
  460. *
  461. * @internal
  462. */
  463. export function collectFields(
  464. exeContext: ExecutionContext,
  465. runtimeType: GraphQLObjectType,
  466. selectionSet: SelectionSetNode,
  467. fields: ObjMap<Array<FieldNode>>,
  468. visitedFragmentNames: ObjMap<boolean>,
  469. ): ObjMap<Array<FieldNode>> {
  470. for (const selection of selectionSet.selections) {
  471. switch (selection.kind) {
  472. case Kind.FIELD: {
  473. if (!shouldIncludeNode(exeContext, selection)) {
  474. continue;
  475. }
  476. const name = getFieldEntryKey(selection);
  477. if (!fields[name]) {
  478. fields[name] = [];
  479. }
  480. fields[name].push(selection);
  481. break;
  482. }
  483. case Kind.INLINE_FRAGMENT: {
  484. if (
  485. !shouldIncludeNode(exeContext, selection) ||
  486. !doesFragmentConditionMatch(exeContext, selection, runtimeType)
  487. ) {
  488. continue;
  489. }
  490. collectFields(
  491. exeContext,
  492. runtimeType,
  493. selection.selectionSet,
  494. fields,
  495. visitedFragmentNames,
  496. );
  497. break;
  498. }
  499. case Kind.FRAGMENT_SPREAD: {
  500. const fragName = selection.name.value;
  501. if (
  502. visitedFragmentNames[fragName] ||
  503. !shouldIncludeNode(exeContext, selection)
  504. ) {
  505. continue;
  506. }
  507. visitedFragmentNames[fragName] = true;
  508. const fragment = exeContext.fragments[fragName];
  509. if (
  510. !fragment ||
  511. !doesFragmentConditionMatch(exeContext, fragment, runtimeType)
  512. ) {
  513. continue;
  514. }
  515. collectFields(
  516. exeContext,
  517. runtimeType,
  518. fragment.selectionSet,
  519. fields,
  520. visitedFragmentNames,
  521. );
  522. break;
  523. }
  524. }
  525. }
  526. return fields;
  527. }
  528. /**
  529. * Determines if a field should be included based on the @include and @skip
  530. * directives, where @skip has higher precedence than @include.
  531. */
  532. function shouldIncludeNode(
  533. exeContext: ExecutionContext,
  534. node: FragmentSpreadNode | FieldNode | InlineFragmentNode,
  535. ): boolean {
  536. const skip = getDirectiveValues(
  537. GraphQLSkipDirective,
  538. node,
  539. exeContext.variableValues,
  540. );
  541. if (skip?.if === true) {
  542. return false;
  543. }
  544. const include = getDirectiveValues(
  545. GraphQLIncludeDirective,
  546. node,
  547. exeContext.variableValues,
  548. );
  549. if (include?.if === false) {
  550. return false;
  551. }
  552. return true;
  553. }
  554. /**
  555. * Determines if a fragment is applicable to the given type.
  556. */
  557. function doesFragmentConditionMatch(
  558. exeContext: ExecutionContext,
  559. fragment: FragmentDefinitionNode | InlineFragmentNode,
  560. type: GraphQLObjectType,
  561. ): boolean {
  562. const typeConditionNode = fragment.typeCondition;
  563. if (!typeConditionNode) {
  564. return true;
  565. }
  566. const conditionalType = typeFromAST(exeContext.schema, typeConditionNode);
  567. if (conditionalType === type) {
  568. return true;
  569. }
  570. if (isAbstractType(conditionalType)) {
  571. return exeContext.schema.isSubType(conditionalType, type);
  572. }
  573. return false;
  574. }
  575. /**
  576. * Implements the logic to compute the key of a given field's entry
  577. */
  578. function getFieldEntryKey(node: FieldNode): string {
  579. return node.alias ? node.alias.value : node.name.value;
  580. }
  581. /**
  582. * Resolves the field on the given source object. In particular, this
  583. * figures out the value that the field returns by calling its resolve function,
  584. * then calls completeValue to complete promises, serialize scalars, or execute
  585. * the sub-selection-set for objects.
  586. */
  587. function resolveField(
  588. exeContext: ExecutionContext,
  589. parentType: GraphQLObjectType,
  590. source: mixed,
  591. fieldNodes: $ReadOnlyArray<FieldNode>,
  592. path: Path,
  593. ): PromiseOrValue<mixed> {
  594. const fieldNode = fieldNodes[0];
  595. const fieldName = fieldNode.name.value;
  596. const fieldDef = getFieldDef(exeContext.schema, parentType, fieldName);
  597. if (!fieldDef) {
  598. return;
  599. }
  600. const resolveFn = fieldDef.resolve ?? exeContext.fieldResolver;
  601. const info = buildResolveInfo(
  602. exeContext,
  603. fieldDef,
  604. fieldNodes,
  605. parentType,
  606. path,
  607. );
  608. // Get the resolve function, regardless of if its result is normal
  609. // or abrupt (error).
  610. const result = resolveFieldValueOrError(
  611. exeContext,
  612. fieldDef,
  613. fieldNodes,
  614. resolveFn,
  615. source,
  616. info,
  617. );
  618. return completeValueCatchingError(
  619. exeContext,
  620. fieldDef.type,
  621. fieldNodes,
  622. info,
  623. path,
  624. result,
  625. );
  626. }
  627. /**
  628. * @internal
  629. */
  630. export function buildResolveInfo(
  631. exeContext: ExecutionContext,
  632. fieldDef: GraphQLField<mixed, mixed>,
  633. fieldNodes: $ReadOnlyArray<FieldNode>,
  634. parentType: GraphQLObjectType,
  635. path: Path,
  636. ): GraphQLResolveInfo {
  637. // The resolve function's optional fourth argument is a collection of
  638. // information about the current execution state.
  639. return {
  640. fieldName: fieldDef.name,
  641. fieldNodes,
  642. returnType: fieldDef.type,
  643. parentType,
  644. path,
  645. schema: exeContext.schema,
  646. fragments: exeContext.fragments,
  647. rootValue: exeContext.rootValue,
  648. operation: exeContext.operation,
  649. variableValues: exeContext.variableValues,
  650. };
  651. }
  652. /**
  653. * Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField`
  654. * function. Returns the result of resolveFn or the abrupt-return Error object.
  655. *
  656. * @internal
  657. */
  658. export function resolveFieldValueOrError(
  659. exeContext: ExecutionContext,
  660. fieldDef: GraphQLField<mixed, mixed>,
  661. fieldNodes: $ReadOnlyArray<FieldNode>,
  662. resolveFn: GraphQLFieldResolver<mixed, mixed>,
  663. source: mixed,
  664. info: GraphQLResolveInfo,
  665. ): Error | mixed {
  666. try {
  667. // Build a JS object of arguments from the field.arguments AST, using the
  668. // variables scope to fulfill any variable references.
  669. // TODO: find a way to memoize, in case this field is within a List type.
  670. const args = getArgumentValues(
  671. fieldDef,
  672. fieldNodes[0],
  673. exeContext.variableValues,
  674. );
  675. // The resolve function's optional third argument is a context value that
  676. // is provided to every resolve function within an execution. It is commonly
  677. // used to represent an authenticated user, or request-specific caches.
  678. const contextValue = exeContext.contextValue;
  679. const result = resolveFn(source, args, contextValue, info);
  680. return isPromise(result) ? result.then(undefined, asErrorInstance) : result;
  681. } catch (error) {
  682. return asErrorInstance(error);
  683. }
  684. }
  685. // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a
  686. // consistent Error interface.
  687. function asErrorInstance(error: mixed): Error {
  688. if (error instanceof Error) {
  689. return error;
  690. }
  691. return new Error('Unexpected error value: ' + inspect(error));
  692. }
  693. // This is a small wrapper around completeValue which detects and logs errors
  694. // in the execution context.
  695. function completeValueCatchingError(
  696. exeContext: ExecutionContext,
  697. returnType: GraphQLOutputType,
  698. fieldNodes: $ReadOnlyArray<FieldNode>,
  699. info: GraphQLResolveInfo,
  700. path: Path,
  701. result: mixed,
  702. ): PromiseOrValue<mixed> {
  703. try {
  704. let completed;
  705. if (isPromise(result)) {
  706. completed = result.then((resolved) =>
  707. completeValue(exeContext, returnType, fieldNodes, info, path, resolved),
  708. );
  709. } else {
  710. completed = completeValue(
  711. exeContext,
  712. returnType,
  713. fieldNodes,
  714. info,
  715. path,
  716. result,
  717. );
  718. }
  719. if (isPromise(completed)) {
  720. // Note: we don't rely on a `catch` method, but we do expect "thenable"
  721. // to take a second callback for the error case.
  722. return completed.then(undefined, (error) =>
  723. handleFieldError(error, fieldNodes, path, returnType, exeContext),
  724. );
  725. }
  726. return completed;
  727. } catch (error) {
  728. return handleFieldError(error, fieldNodes, path, returnType, exeContext);
  729. }
  730. }
  731. function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) {
  732. const error = locatedError(
  733. asErrorInstance(rawError),
  734. fieldNodes,
  735. pathToArray(path),
  736. );
  737. // If the field type is non-nullable, then it is resolved without any
  738. // protection from errors, however it still properly locates the error.
  739. if (isNonNullType(returnType)) {
  740. throw error;
  741. }
  742. // Otherwise, error protection is applied, logging the error and resolving
  743. // a null value for this field if one is encountered.
  744. exeContext.errors.push(error);
  745. return null;
  746. }
  747. /**
  748. * Implements the instructions for completeValue as defined in the
  749. * "Field entries" section of the spec.
  750. *
  751. * If the field type is Non-Null, then this recursively completes the value
  752. * for the inner type. It throws a field error if that completion returns null,
  753. * as per the "Nullability" section of the spec.
  754. *
  755. * If the field type is a List, then this recursively completes the value
  756. * for the inner type on each item in the list.
  757. *
  758. * If the field type is a Scalar or Enum, ensures the completed value is a legal
  759. * value of the type by calling the `serialize` method of GraphQL type
  760. * definition.
  761. *
  762. * If the field is an abstract type, determine the runtime type of the value
  763. * and then complete based on that type
  764. *
  765. * Otherwise, the field type expects a sub-selection set, and will complete the
  766. * value by evaluating all sub-selections.
  767. */
  768. function completeValue(
  769. exeContext: ExecutionContext,
  770. returnType: GraphQLOutputType,
  771. fieldNodes: $ReadOnlyArray<FieldNode>,
  772. info: GraphQLResolveInfo,
  773. path: Path,
  774. result: mixed,
  775. ): PromiseOrValue<mixed> {
  776. // If result is an Error, throw a located error.
  777. if (result instanceof Error) {
  778. throw result;
  779. }
  780. // If field type is NonNull, complete for inner type, and throw field error
  781. // if result is null.
  782. if (isNonNullType(returnType)) {
  783. const completed = completeValue(
  784. exeContext,
  785. returnType.ofType,
  786. fieldNodes,
  787. info,
  788. path,
  789. result,
  790. );
  791. if (completed === null) {
  792. throw new Error(
  793. `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`,
  794. );
  795. }
  796. return completed;
  797. }
  798. // If result value is null or undefined then return null.
  799. if (result == null) {
  800. return null;
  801. }
  802. // If field type is List, complete each item in the list with the inner type
  803. if (isListType(returnType)) {
  804. return completeListValue(
  805. exeContext,
  806. returnType,
  807. fieldNodes,
  808. info,
  809. path,
  810. result,
  811. );
  812. }
  813. // If field type is a leaf type, Scalar or Enum, serialize to a valid value,
  814. // returning null if serialization is not possible.
  815. if (isLeafType(returnType)) {
  816. return completeLeafValue(returnType, result);
  817. }
  818. // If field type is an abstract type, Interface or Union, determine the
  819. // runtime Object type and complete for that type.
  820. if (isAbstractType(returnType)) {
  821. return completeAbstractValue(
  822. exeContext,
  823. returnType,
  824. fieldNodes,
  825. info,
  826. path,
  827. result,
  828. );
  829. }
  830. // If field type is Object, execute and complete all sub-selections.
  831. // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')
  832. if (isObjectType(returnType)) {
  833. return completeObjectValue(
  834. exeContext,
  835. returnType,
  836. fieldNodes,
  837. info,
  838. path,
  839. result,
  840. );
  841. }
  842. // istanbul ignore next (Not reachable. All possible output types have been considered)
  843. invariant(
  844. false,
  845. 'Cannot complete value of unexpected output type: ' +
  846. inspect((returnType: empty)),
  847. );
  848. }
  849. /**
  850. * Complete a list value by completing each item in the list with the
  851. * inner type
  852. */
  853. function completeListValue(
  854. exeContext: ExecutionContext,
  855. returnType: GraphQLList<GraphQLOutputType>,
  856. fieldNodes: $ReadOnlyArray<FieldNode>,
  857. info: GraphQLResolveInfo,
  858. path: Path,
  859. result: mixed,
  860. ): PromiseOrValue<$ReadOnlyArray<mixed>> {
  861. if (!isCollection(result)) {
  862. throw new GraphQLError(
  863. `Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`,
  864. );
  865. }
  866. // This is specified as a simple map, however we're optimizing the path
  867. // where the list contains no Promises by avoiding creating another Promise.
  868. const itemType = returnType.ofType;
  869. let containsPromise = false;
  870. const completedResults = arrayFrom(result, (item, index) => {
  871. // No need to modify the info object containing the path,
  872. // since from here on it is not ever accessed by resolver functions.
  873. const fieldPath = addPath(path, index, undefined);
  874. const completedItem = completeValueCatchingError(
  875. exeContext,
  876. itemType,
  877. fieldNodes,
  878. info,
  879. fieldPath,
  880. item,
  881. );
  882. if (!containsPromise && isPromise(completedItem)) {
  883. containsPromise = true;
  884. }
  885. return completedItem;
  886. });
  887. return containsPromise ? Promise.all(completedResults) : completedResults;
  888. }
  889. /**
  890. * Complete a Scalar or Enum by serializing to a valid value, returning
  891. * null if serialization is not possible.
  892. */
  893. function completeLeafValue(returnType: GraphQLLeafType, result: mixed): mixed {
  894. const serializedResult = returnType.serialize(result);
  895. if (serializedResult === undefined) {
  896. throw new Error(
  897. `Expected a value of type "${inspect(returnType)}" but ` +
  898. `received: ${inspect(result)}`,
  899. );
  900. }
  901. return serializedResult;
  902. }
  903. /**
  904. * Complete a value of an abstract type by determining the runtime object type
  905. * of that value, then complete the value for that type.
  906. */
  907. function completeAbstractValue(
  908. exeContext: ExecutionContext,
  909. returnType: GraphQLAbstractType,
  910. fieldNodes: $ReadOnlyArray<FieldNode>,
  911. info: GraphQLResolveInfo,
  912. path: Path,
  913. result: mixed,
  914. ): PromiseOrValue<ObjMap<mixed>> {
  915. const resolveTypeFn = returnType.resolveType ?? exeContext.typeResolver;
  916. const contextValue = exeContext.contextValue;
  917. const runtimeType = resolveTypeFn(result, contextValue, info, returnType);
  918. if (isPromise(runtimeType)) {
  919. return runtimeType.then((resolvedRuntimeType) =>
  920. completeObjectValue(
  921. exeContext,
  922. ensureValidRuntimeType(
  923. resolvedRuntimeType,
  924. exeContext,
  925. returnType,
  926. fieldNodes,
  927. info,
  928. result,
  929. ),
  930. fieldNodes,
  931. info,
  932. path,
  933. result,
  934. ),
  935. );
  936. }
  937. return completeObjectValue(
  938. exeContext,
  939. ensureValidRuntimeType(
  940. runtimeType,
  941. exeContext,
  942. returnType,
  943. fieldNodes,
  944. info,
  945. result,
  946. ),
  947. fieldNodes,
  948. info,
  949. path,
  950. result,
  951. );
  952. }
  953. function ensureValidRuntimeType(
  954. runtimeTypeOrName: ?GraphQLObjectType | string,
  955. exeContext: ExecutionContext,
  956. returnType: GraphQLAbstractType,
  957. fieldNodes: $ReadOnlyArray<FieldNode>,
  958. info: GraphQLResolveInfo,
  959. result: mixed,
  960. ): GraphQLObjectType {
  961. const runtimeType =
  962. typeof runtimeTypeOrName === 'string'
  963. ? exeContext.schema.getType(runtimeTypeOrName)
  964. : runtimeTypeOrName;
  965. if (!isObjectType(runtimeType)) {
  966. throw new GraphQLError(
  967. `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` +
  968. `value ${inspect(result)}, received "${inspect(runtimeType)}". ` +
  969. `Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`,
  970. fieldNodes,
  971. );
  972. }
  973. if (!exeContext.schema.isSubType(returnType, runtimeType)) {
  974. throw new GraphQLError(
  975. `Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`,
  976. fieldNodes,
  977. );
  978. }
  979. return runtimeType;
  980. }
  981. /**
  982. * Complete an Object value by executing all sub-selections.
  983. */
  984. function completeObjectValue(
  985. exeContext: ExecutionContext,
  986. returnType: GraphQLObjectType,
  987. fieldNodes: $ReadOnlyArray<FieldNode>,
  988. info: GraphQLResolveInfo,
  989. path: Path,
  990. result: mixed,
  991. ): PromiseOrValue<ObjMap<mixed>> {
  992. // If there is an isTypeOf predicate function, call it with the
  993. // current result. If isTypeOf returns false, then raise an error rather
  994. // than continuing execution.
  995. if (returnType.isTypeOf) {
  996. const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);
  997. if (isPromise(isTypeOf)) {
  998. return isTypeOf.then((resolvedIsTypeOf) => {
  999. if (!resolvedIsTypeOf) {
  1000. throw invalidReturnTypeError(returnType, result, fieldNodes);
  1001. }
  1002. return collectAndExecuteSubfields(
  1003. exeContext,
  1004. returnType,
  1005. fieldNodes,
  1006. path,
  1007. result,
  1008. );
  1009. });
  1010. }
  1011. if (!isTypeOf) {
  1012. throw invalidReturnTypeError(returnType, result, fieldNodes);
  1013. }
  1014. }
  1015. return collectAndExecuteSubfields(
  1016. exeContext,
  1017. returnType,
  1018. fieldNodes,
  1019. path,
  1020. result,
  1021. );
  1022. }
  1023. function invalidReturnTypeError(
  1024. returnType: GraphQLObjectType,
  1025. result: mixed,
  1026. fieldNodes: $ReadOnlyArray<FieldNode>,
  1027. ): GraphQLError {
  1028. return new GraphQLError(
  1029. `Expected value of type "${returnType.name}" but got: ${inspect(result)}.`,
  1030. fieldNodes,
  1031. );
  1032. }
  1033. function collectAndExecuteSubfields(
  1034. exeContext: ExecutionContext,
  1035. returnType: GraphQLObjectType,
  1036. fieldNodes: $ReadOnlyArray<FieldNode>,
  1037. path: Path,
  1038. result: mixed,
  1039. ): PromiseOrValue<ObjMap<mixed>> {
  1040. // Collect sub-fields to execute to complete this value.
  1041. const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);
  1042. return executeFields(exeContext, returnType, result, path, subFieldNodes);
  1043. }
  1044. /**
  1045. * A memoized collection of relevant subfields with regard to the return
  1046. * type. Memoizing ensures the subfields are not repeatedly calculated, which
  1047. * saves overhead when resolving lists of values.
  1048. */
  1049. const collectSubfields = memoize3(_collectSubfields);
  1050. function _collectSubfields(
  1051. exeContext: ExecutionContext,
  1052. returnType: GraphQLObjectType,
  1053. fieldNodes: $ReadOnlyArray<FieldNode>,
  1054. ): ObjMap<Array<FieldNode>> {
  1055. let subFieldNodes = Object.create(null);
  1056. const visitedFragmentNames = Object.create(null);
  1057. for (const node of fieldNodes) {
  1058. if (node.selectionSet) {
  1059. subFieldNodes = collectFields(
  1060. exeContext,
  1061. returnType,
  1062. node.selectionSet,
  1063. subFieldNodes,
  1064. visitedFragmentNames,
  1065. );
  1066. }
  1067. }
  1068. return subFieldNodes;
  1069. }
  1070. /**
  1071. * If a resolveType function is not given, then a default resolve behavior is
  1072. * used which attempts two strategies:
  1073. *
  1074. * First, See if the provided value has a `__typename` field defined, if so, use
  1075. * that value as name of the resolved type.
  1076. *
  1077. * Otherwise, test each possible type for the abstract type by calling
  1078. * isTypeOf for the object being coerced, returning the first type that matches.
  1079. */
  1080. export const defaultTypeResolver: GraphQLTypeResolver<mixed, mixed> = function (
  1081. value,
  1082. contextValue,
  1083. info,
  1084. abstractType,
  1085. ) {
  1086. // First, look for `__typename`.
  1087. if (isObjectLike(value) && typeof value.__typename === 'string') {
  1088. return value.__typename;
  1089. }
  1090. // Otherwise, test each possible type.
  1091. const possibleTypes = info.schema.getPossibleTypes(abstractType);
  1092. const promisedIsTypeOfResults = [];
  1093. for (let i = 0; i < possibleTypes.length; i++) {
  1094. const type = possibleTypes[i];
  1095. if (type.isTypeOf) {
  1096. const isTypeOfResult = type.isTypeOf(value, contextValue, info);
  1097. if (isPromise(isTypeOfResult)) {
  1098. promisedIsTypeOfResults[i] = isTypeOfResult;
  1099. } else if (isTypeOfResult) {
  1100. return type;
  1101. }
  1102. }
  1103. }
  1104. if (promisedIsTypeOfResults.length) {
  1105. return Promise.all(promisedIsTypeOfResults).then((isTypeOfResults) => {
  1106. for (let i = 0; i < isTypeOfResults.length; i++) {
  1107. if (isTypeOfResults[i]) {
  1108. return possibleTypes[i];
  1109. }
  1110. }
  1111. });
  1112. }
  1113. };
  1114. /**
  1115. * If a resolve function is not given, then a default resolve behavior is used
  1116. * which takes the property of the source object of the same name as the field
  1117. * and returns it as the result, or if it's a function, returns the result
  1118. * of calling that function while passing along args and context value.
  1119. */
  1120. export const defaultFieldResolver: GraphQLFieldResolver<
  1121. mixed,
  1122. mixed,
  1123. > = function (source: any, args, contextValue, info) {
  1124. // ensure source is a value for which property access is acceptable.
  1125. if (isObjectLike(source) || typeof source === 'function') {
  1126. const property = source[info.fieldName];
  1127. if (typeof property === 'function') {
  1128. return source[info.fieldName](args, contextValue, info);
  1129. }
  1130. return property;
  1131. }
  1132. };
  1133. /**
  1134. * This method looks up the field on the given type definition.
  1135. * It has special casing for the three introspection fields,
  1136. * __schema, __type and __typename. __typename is special because
  1137. * it can always be queried as a field, even in situations where no
  1138. * other fields are allowed, like on a Union. __schema and __type
  1139. * could get automatically added to the query type, but that would
  1140. * require mutating type definitions, which would cause issues.
  1141. *
  1142. * @internal
  1143. */
  1144. export function getFieldDef(
  1145. schema: GraphQLSchema,
  1146. parentType: GraphQLObjectType,
  1147. fieldName: string,
  1148. ): ?GraphQLField<mixed, mixed> {
  1149. if (
  1150. fieldName === SchemaMetaFieldDef.name &&
  1151. schema.getQueryType() === parentType
  1152. ) {
  1153. return SchemaMetaFieldDef;
  1154. } else if (
  1155. fieldName === TypeMetaFieldDef.name &&
  1156. schema.getQueryType() === parentType
  1157. ) {
  1158. return TypeMetaFieldDef;
  1159. } else if (fieldName === TypeNameMetaFieldDef.name) {
  1160. return TypeNameMetaFieldDef;
  1161. }
  1162. return parentType.getFields()[fieldName];
  1163. }