execute.js.flow 34 KB

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