v16 APIgraphql/execution

Execute GraphQL operations and produce GraphQL execution results.

These exports are also available from the root graphql package.

For documentation purposes, these exports are grouped into the following categories:

Category: Execution

Functions

execute()

Implements the “Executing requests” section of the GraphQL specification.

Returns either a synchronous ExecutionResult (if all encountered resolvers are synchronous), or a Promise of an ExecutionResult that will eventually be resolved and never rejected.

If the arguments to this function do not result in a legal execution context, a GraphQLError will be thrown immediately explaining the invalid input.

Field errors are collected into the response instead of rejecting the returned promise. Only the field that produced the error and its descendants are omitted; sibling fields continue to execute. Errors from fields of non-null type may propagate to the nearest nullable parent, which can be the entire response data.

Signature:

execute(
  args: ExecutionArgs,
): PromiseOrValue<ExecutionResult>;

Arguments
NameTypeDescription
argsExecutionArgsThe arguments used to perform the operation.

Returns
TypeDescription
PromiseOrValue<ExecutionResult>A completed execution result, or a promise resolving to one when execution is asynchronous.

Example 1
// Execute an asynchronous operation with variables.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { execute } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    greeting(name: String!): String
  }
`);
 
const result = await execute({
  schema,
  document: parse('query ($name: String!) { greeting(name: $name) }'),
  rootValue: {
    greeting: ({ name }) => `Hello, ${name}!`,
  },
  variableValues: { name: 'Ada' },
});
 
result; // => { data: { greeting: 'Hello, Ada!' } }

Example 2
// This variant supplies context plus custom field and type resolvers.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { execute } from 'graphql/execution';
 
const schema = buildSchema(`
  interface Named {
    name: String!
  }
 
  type User implements Named {
    name: String!
  }
 
  type Query {
    viewer: Named
  }
`);
 
const result = await execute({
  schema,
  document: parse('query Viewer { viewer { __typename name } }'),
  rootValue: { viewer: { kind: 'user', name: 'Ada' } },
  contextValue: { locale: 'en' },
  operationName: 'Viewer',
  fieldResolver: (source, _args, contextValue, info) => {
    contextValue.locale; // => 'en'
    return source[info.fieldName];
  },
  typeResolver: (value) => {
    return value.kind === 'user' ? 'User' : undefined;
  },
});
 
result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } }

Example 3
// This variant shows how resolver errors become field errors in the result.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { execute } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    broken: String
  }
`);
const document = parse('{ broken }');
 
const result = await execute({
  schema,
  document,
  rootValue: {
    broken: () => {
      throw new Error('Resolver failed.');
    },
  },
});
 
result.data.broken; // => null
result.errors[0].message; // => 'Resolver failed.'

Example 4
// This variant limits how many variable coercion errors are reported.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { execute } from 'graphql/execution';
 
const schema = buildSchema(`
  input ReviewInput {
    stars: Int!
  }
 
  type Query {
    review(input: ReviewInput!): String
  }
`);
const document = parse(`
  query ($first: ReviewInput!, $second: ReviewInput!) {
    first: review(input: $first)
    second: review(input: $second)
  }
`);
 
const result = await execute({
  schema,
  document,
  variableValues: {
    first: { stars: 'bad' },
    second: { stars: 'also bad' },
  },
  options: { maxCoercionErrors: 1 },
});
 
result.errors.length; // => 2
result.errors[1].message; // matches /error limit reached/

executeSync()

Also implements the “Executing requests” section of the GraphQL specification. However, it guarantees to complete synchronously (or throw an error) assuming that all field resolvers are also synchronous.

Signature:

executeSync(
  args: ExecutionArgs,
): ExecutionResult;

Arguments
NameTypeDescription
argsExecutionArgsThe arguments used to perform the operation.

Returns
TypeDescription
ExecutionResultCompleted execution output for a synchronous operation.

Example 1
// Execute an operation synchronously when all resolvers are synchronous.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { executeSync } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    greeting: String
  }
`);
const document = parse('{ greeting }');
 
const result = executeSync({
  schema,
  document,
  rootValue: {
    greeting: 'Hello',
  },
});
 
result; // => { data: { greeting: 'Hello' } }

Example 2
// This variant shows executeSync throwing when a resolver returns a promise.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { executeSync } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    greeting: String
  }
`);
 
executeSync({
  schema,
  document: parse('{ greeting }'),
  rootValue: {
    greeting: async () => 'Hello',
  },
}); // throws an error

Constants

defaultTypeResolver

If a resolveType function is not given, then a default resolve behavior is used which attempts two strategies:

First, See if the provided value has a __typename field defined, if so, use that value as name of the resolved type.

Otherwise, test each possible type for the abstract type by calling isTypeOf for the object being coerced, returning the first type that matches.


Type
GraphQLTypeResolver<unknown, unknown>

defaultFieldResolver

If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it’s a function, returns the result of calling that function while passing along args and context value.


Type
GraphQLFieldResolver<unknown, unknown>

Types

ExecutionResult

Interface. Represents the response produced by executing a GraphQL operation.


Type Parameters
NameConstraintDefaultDescription
TDataObjMap<unknown>Shape of the execution data payload.
TExtensionsObjMap<unknown>Shape of the extensions payload.

Members
NameTypeDescription
errors?readonly GraphQLError[]Errors raised while parsing, validating, or executing the operation.
data?TData | nullData returned by execution, or null when execution could not produce data.
extensions?TExtensionsExtension fields to include in the formatted result.

FormattedExecutionResult

Interface. A JSON-serializable GraphQL execution result.


Type Parameters
NameConstraintDefaultDescription
TDataObjMap<unknown>Shape of the formatted data payload.
TExtensionsObjMap<unknown>Shape of the formatted extensions payload.

Members
NameTypeDescription
errors?readonly GraphQLFormattedError[]Errors raised while parsing, validating, or executing the operation.
data?TData | nullData returned by execution, or null when execution could not produce data.
extensions?TExtensionsExtension fields to include in the formatted result.

ExecutionArgs

Interface. Arguments accepted by execute and executeSync.


Members
NameTypeDescription
schemaGraphQLSchemaThe schema used for validation or execution.
documentDocumentNodeThe parsed GraphQL document to execute.
rootValue?unknownInitial root value passed to the operation.
contextValue?unknownApplication context value passed to every resolver.
variableValues?Maybe<{ readonly [variable: string]: unknown; }>Runtime variable values keyed by variable name.
operationName?Maybe<string>Name of the operation to execute when the document contains multiple operations.
fieldResolver?Maybe<GraphQLFieldResolver<any, any>>Resolver used when a field does not define its own resolver.
typeResolver?Maybe<GraphQLTypeResolver<any, any>>Resolver used when an abstract type does not define its own resolver.
subscribeFieldResolver?Maybe<GraphQLFieldResolver<any, any>>Resolver used for the root subscription field.
options?{ maxCoercionErrors?: number }Additional execution options.

Category: Subscriptions

Functions

subscribe()

Implements the “Subscribe” algorithm described in the GraphQL specification.

Returns a Promise that resolves to either an AsyncIterator (if successful) or an ExecutionResult (error). The promise will be rejected if the schema or other arguments to this function are invalid, or if the resolved event stream is not an async iterable.

If the client-provided arguments to this function do not result in a compliant subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no data will be returned.

If the source stream could not be created due to faulty subscription resolver logic or underlying systems, the promise will resolve to a single ExecutionResult containing errors and no data.

If the operation succeeded, the promise resolves to an AsyncIterator, which yields a stream of ExecutionResults representing the response stream.

Each payload yielded by the source event stream is executed with the payload as the root value. This maps the subscription source stream into the response stream described by the GraphQL specification.

Accepts an object with named arguments.

Signature:

subscribe(
  args: ExecutionArgs,
): Promise<
  ExecutionResult | AsyncGenerator<ExecutionResult, void, void>
>;

Arguments
NameTypeDescription
argsExecutionArgsThe arguments used to perform the operation.

Returns
TypeDescription
Promise< ExecutionResult | AsyncGenerator<ExecutionResult, void, void> >A source stream mapped to execution results, or an execution result
containing subscription errors.

Example 1
// Use a same-named rootValue function to provide the source event stream.
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { subscribe } from 'graphql/execution';
 
async function* greetings() {
  yield { greeting: 'Hello' };
  yield { greeting: 'Bonjour' };
}
 
const schema = buildSchema(`
  type Query {
    noop: String
  }
 
  type Subscription {
    greeting: String
  }
`);
 
const result = await subscribe({
  schema,
  document: parse('subscription { greeting }'),
  rootValue: { greeting: () => greetings() },
});
 
assert('next' in result);
 
const firstPayload = await result.next();
firstPayload.value; // => { data: { greeting: 'Hello' } }

Example 2
// This variant supplies events through a custom subscribeFieldResolver.
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { subscribe } from 'graphql/execution';
 
async function* defaultGreetings() {
  yield { greeting: 'Hello' };
}
 
async function* frenchGreetings() {
  yield { greeting: 'Bonjour' };
}
 
const schema = buildSchema(`
  type Query {
    noop: String
  }
 
  type Subscription {
    greeting(locale: String): String
  }
`);
 
const result = await subscribe({
  schema,
  document: parse(
    'subscription Greeting($locale: String) { greeting(locale: $locale) }',
  ),
  rootValue: {
    greeting: (args, contextValue) => {
      const locale = args.locale ?? contextValue.defaultLocale;
      return locale === 'fr' ? frenchGreetings() : defaultGreetings();
    },
  },
  contextValue: { defaultLocale: 'fr' },
  variableValues: { locale: 'fr' },
  operationName: 'Greeting',
  subscribeFieldResolver: (rootValue, args, contextValue, info) => {
    args.locale; // => 'fr'
    return rootValue[info.fieldName](args, contextValue);
  },
});
 
assert('next' in result);
 
const firstPayload = await result.next();
firstPayload.value; // => { data: { greeting: 'Bonjour' } }

Example 3
// This variant shows the error result when the schema has no subscription root.
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { subscribe } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    noop: String
  }
`);
 
const result = await subscribe({
  schema,
  document: parse('subscription { greeting }'),
});
 
assert('errors' in result);
 
result.errors[0].message; // => 'Schema is not configured to execute subscription operation.'

createSourceEventStream()


Overload 1

Implements the “CreateSourceEventStream” algorithm described in the GraphQL specification, resolving the subscription source event stream.

Returns a Promise that resolves to either an AsyncIterable (if successful) or an ExecutionResult (error). The promise will be rejected if the schema or other arguments to this function are invalid, or if the resolved event stream is not an async iterable.

If the client-provided arguments to this function do not result in a compliant subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no data will be returned.

If the source stream could not be created due to faulty subscription resolver logic or underlying systems, the promise will resolve to a single ExecutionResult containing errors and no data.

If the operation succeeded, the promise resolves to the AsyncIterable for the event stream returned by the resolver.

A Source Event Stream represents a sequence of events, each of which triggers a GraphQL execution for that event.

This may be useful when hosting the stateful subscription service in a different process or machine than the stateless GraphQL execution engine, or otherwise separating these two steps. For more on this, see the “Supporting Subscriptions at Scale” information in the GraphQL specification.

Signature:

createSourceEventStream(
  args: ExecutionArgs,
): Promise<
  ExecutionResult | AsyncIterable<unknown, any, any>
>;

Arguments
NameTypeDescription
argsExecutionArgsThe arguments used to perform the operation.

Returns
TypeDescription
Promise< ExecutionResult | AsyncIterable<unknown, any, any> >The source event stream, or an execution result containing subscription errors.

Example
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { createSourceEventStream } from 'graphql/execution';
 
async function* greetings() {
  yield { greeting: 'Hello' };
}
 
const schema = buildSchema(`
  type Query {
    noop: String
  }
 
  type Subscription {
    greeting: String
  }
`);
 
const stream = await createSourceEventStream({
  schema,
  document: parse('subscription { greeting }'),
  rootValue: { greeting: () => greetings() },
});
 
Symbol.asyncIterator in stream; // => true

Overload 2

Creates the source event stream for a subscription operation using the legacy positional argument overload. This deprecated overload will be removed in the next major version; use the args object overload instead.

Signature:

createSourceEventStream(
  schema: GraphQLSchema,
  document: DocumentNode,
  rootValue?: unknown,
  contextValue?: unknown,
  variableValues?: Maybe<{
    readonly [variable: string]: unknown;
  }>,
  operationName?: Maybe<string>,
  subscribeFieldResolver?: Maybe<GraphQLFieldResolver<any, any>>,
): Promise<
  ExecutionResult | AsyncIterable<unknown, any, any>
>;

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.
documentDocumentNodeThe parsed GraphQL document containing the subscription
operation.
rootValue?unknownInitial root value passed to the subscription resolver.
contextValue?unknownApplication context value passed to resolvers.
variableValues?Maybe<{ readonly [variable: string]: unknown; }>Runtime variable values keyed by variable name.
operationName?Maybe<string>Name of the subscription operation to execute when
the document contains multiple operations.
subscribeFieldResolver?Maybe<GraphQLFieldResolver<any, any>>Resolver used for the root subscription
field.

Returns
TypeDescription
Promise< ExecutionResult | AsyncIterable<unknown, any, any> >The source event stream, or an execution result containing
subscription errors.

Example
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { createSourceEventStream } from 'graphql/execution';
 
async function* greetings() {
  yield { greeting: 'Hello' };
}
 
const schema = buildSchema(`
  type Query {
    noop: String
  }
 
  type Subscription {
    greeting: String
  }
`);
const document = parse('subscription { greeting }');
 
const stream = await createSourceEventStream(schema, document, {
  greeting: () => greetings(),
});
 
Symbol.asyncIterator in stream; // => true

Category: Values

Functions

getVariableValues()

Prepares an object map of variableValues of the correct type based on the provided variable definitions and arbitrary input. If the input cannot be parsed to match the variable definitions, GraphQLError values are returned.

Note: Returned value is a plain Object with a prototype, since it is exposed to user code. Care should be taken to not pull values from the Object prototype.

Signature:

getVariableValues(
  schema: GraphQLSchema,
  varDefNodes: readonly VariableDefinitionNode[],
  inputs: { readonly [variable: string]: unknown },
  options?: GetVariableValuesOptions,
):
  | {
      errors: ReadonlyArray<GraphQLError>;
      coerced?: never;
    }
  | {
      coerced: { [variable: string]: unknown };
      errors?: never;
    };

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.
varDefNodesreadonly VariableDefinitionNode[]The variable definition AST nodes to coerce.
inputs{ readonly [variable: string]: unknown }The runtime variable values keyed by variable name.
options?GetVariableValuesOptionsOptional variable coercion options, including error limits.

Returns
TypeDescription
| { errors: ReadonlyArray<GraphQLError>; coerced?: never; } | { coerced: { [variable: string]: unknown }; errors?: never; }Coerced variable values, or request errors.

Example 1
// Coerce provided variables and apply operation defaults.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { getVariableValues } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    reviews(stars: Int!, limit: Int = 10): [String]
  }
`);
const document = parse(`
  query ($stars: Int!, $limit: Int = 10) {
    reviews(stars: $stars, limit: $limit)
  }
`);
const operation = document.definitions[0];
 
const result = getVariableValues(
  schema,
  operation.variableDefinitions,
  { stars: '5' },
);
 
result; // => { coerced: { stars: 5, limit: 10 } }

Example 2
// This variant uses maxErrors to cap reported coercion errors.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { getVariableValues } from 'graphql/execution';
 
const schema = buildSchema(`
  input ReviewInput {
    stars: Int!
  }
 
  type Query {
    review(input: ReviewInput!): String
  }
`);
const document = parse(`
  query ($first: ReviewInput!, $second: ReviewInput!) {
    first: review(input: $first)
    second: review(input: $second)
  }
`);
const operation = document.definitions[0];
 
const result = getVariableValues(
  schema,
  operation.variableDefinitions,
  { first: { stars: 'bad' }, second: { stars: 'also bad' } },
  { maxErrors: 1 },
);
 
result.errors.length; // => 2
result.errors[1].message; // matches /error limit reached/

getArgumentValues()

Prepares an object map of argument values given a list of argument definitions and list of argument AST nodes.

Note: Returned value is a plain Object with a prototype, since it is exposed to user code. Care should be taken to not pull values from the Object prototype.

Signature:

getArgumentValues(
  def:
    | GraphQLField<unknown, unknown>
    | GraphQLDirective,
  node: FieldNode | DirectiveNode,
  variableValues?: Maybe<ObjMap<unknown>>,
): { [argument: string]: unknown };

Arguments
NameTypeDescription
defGraphQLField<unknown, unknown> | GraphQLDirectiveThe field or directive definition whose arguments should be coerced.
nodeFieldNode | DirectiveNodeThe AST node to inspect.
variableValues?Maybe<ObjMap<unknown>>The runtime variable values keyed by variable name.

Returns
TypeDescription
{ [argument: string]: unknown }Coerced argument values keyed by argument name.

Example 1
// Read literal argument values and defaults.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { getArgumentValues } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    reviews(stars: Int!, limit: Int = 10): [String]
  }
`);
const fieldDef = schema.getQueryType().getFields().reviews;
const document = parse('{ reviews(stars: 5) }');
const fieldNode = document.definitions[0].selectionSet.selections[0];
 
getArgumentValues(fieldDef, fieldNode); // => { stars: 5, limit: 10 }

Example 2
// This variant resolves argument values from operation variables.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { getArgumentValues } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    reviews(stars: Int!): [String]
  }
`);
const fieldDef = schema.getQueryType().getFields().reviews;
const document = parse('query ($stars: Int!) { reviews(stars: $stars) }');
const fieldNode = document.definitions[0].selectionSet.selections[0];
 
getArgumentValues(fieldDef, fieldNode, { stars: 5 }); // => { stars: 5 }
getArgumentValues(fieldDef, fieldNode, {}); // throws an error

getDirectiveValues()

Prepares an object map of argument values given a directive definition and a AST node which may contain directives. Optionally also accepts a map of variable values.

If the directive does not exist on the node, returns undefined.

Note: Returned value is a plain Object with a prototype, since it is exposed to user code. Care should be taken to not pull values from the Object prototype.

Signature:

getDirectiveValues(
  directiveDef: GraphQLDirective,
  node: DirectiveValuesNode,
  variableValues?: Maybe<ObjMap<unknown>>,
): { [argument: string]: unknown } | undefined;

Arguments
NameTypeDescription
directiveDefGraphQLDirectiveThe directive definition whose arguments should be coerced.
nodeDirectiveValuesNodeThe AST node to inspect.
variableValues?Maybe<ObjMap<unknown>>The runtime variable values keyed by variable name.

Returns
TypeDescription
{ [argument: string]: unknown } | undefinedCoerced directive argument values keyed by argument name.

Example 1
// Read literal directive arguments from a node.
import { parse } from 'graphql/language';
import { GraphQLSkipDirective } from 'graphql/type';
import { getDirectiveValues } from 'graphql/execution';
 
const document = parse('{ name @skip(if: true) }');
const fieldNode = document.definitions[0].selectionSet.selections[0];
 
getDirectiveValues(GraphQLSkipDirective, fieldNode); // => { if: true }

Example 2
// This variant resolves directive arguments from variables and handles absent directives.
import { parse } from 'graphql/language';
import { GraphQLIncludeDirective } from 'graphql/type';
import { getDirectiveValues } from 'graphql/execution';
 
const document = parse('query ($includeName: Boolean!) { name @include(if: $includeName) }');
const fieldNode = document.definitions[0].selectionSet.selections[0];
 
getDirectiveValues(GraphQLIncludeDirective, fieldNode, {
  includeName: false,
}); // => { if: false }
getDirectiveValues(GraphQLIncludeDirective, { directives: [] }); // => undefined

Category: Paths

Functions

responsePathAsArray()

Given a Path, return an Array of the path keys.

Signature:

responsePathAsArray(
  path: Maybe<
    Readonly<Path>
  >,
): (string | number)[];

Arguments
NameTypeDescription
pathMaybe<Readonly<Path>>The linked response path to flatten.

Returns
TypeDescription
(string | number)[]An array of response path keys from root to leaf.

Example
import { pathToArray } from 'graphql/jsutils/Path';
 
const path = {
  prev: {
    prev: {
      prev: undefined,
      key: 'viewer',
      typename: 'Query',
    },
    key: 'friends',
    typename: 'User',
  },
  key: 0,
  typename: undefined,
};
 
pathToArray(path); // => ['viewer', 'friends', 0]
pathToArray(undefined); // => []