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()executeSync()
Constants:
defaultTypeResolverdefaultFieldResolver
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>;
| Name | Type | Description |
|---|---|---|
| args | ExecutionArgs | The arguments used to perform the operation. |
| Type | Description |
|---|---|
PromiseOrValue<ExecutionResult> | A completed execution result, or a promise resolving to one when execution is asynchronous. |
// 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!' } }// 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' } } }// 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.'// 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;
| Name | Type | Description |
|---|---|---|
| args | ExecutionArgs | The arguments used to perform the operation. |
| Type | Description |
|---|---|
ExecutionResult | Completed execution output for a synchronous operation. |
// 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' } }// 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 errorConstants
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.
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.
GraphQLFieldResolver<unknown, unknown>
Types
ExecutionResult
Interface. Represents the response produced by executing a GraphQL operation.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TData | ObjMap<unknown> | Shape of the execution data payload. | |
| TExtensions | ObjMap<unknown> | Shape of the extensions payload. |
| Name | Type | Description |
|---|---|---|
| errors? | readonly GraphQLError[] | Errors raised while parsing, validating, or executing the operation. |
| data? | TData | null | Data returned by execution, or null when execution could not produce data. |
| extensions? | TExtensions | Extension fields to include in the formatted result. |
FormattedExecutionResult
Interface. A JSON-serializable GraphQL execution result.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TData | ObjMap<unknown> | Shape of the formatted data payload. | |
| TExtensions | ObjMap<unknown> | Shape of the formatted extensions payload. |
| Name | Type | Description |
|---|---|---|
| errors? | readonly GraphQLFormattedError[] | Errors raised while parsing, validating, or executing the operation. |
| data? | TData | null | Data returned by execution, or null when execution could not produce data. |
| extensions? | TExtensions | Extension fields to include in the formatted result. |
ExecutionArgs
Interface. Arguments accepted by execute and executeSync.
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | The schema used for validation or execution. |
| document | DocumentNode | The parsed GraphQL document to execute. |
| rootValue? | unknown | Initial root value passed to the operation. |
| contextValue? | unknown | Application 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()createSourceEventStream()
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>
>;
| Name | Type | Description |
|---|---|---|
| args | ExecutionArgs | The arguments used to perform the operation. |
| Type | Description |
|---|---|
Promise<
ExecutionResult | AsyncGenerator<ExecutionResult, void, void>
> | A source stream mapped to execution results, or an execution result containing subscription errors. |
// 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' } }// 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' } }// 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()
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>
>;
| Name | Type | Description |
|---|---|---|
| args | ExecutionArgs | The arguments used to perform the operation. |
| Type | Description |
|---|---|
Promise<
ExecutionResult | AsyncIterable<unknown, any, any>
> | The source event stream, or an execution result containing subscription errors. |
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; // => trueCreates 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>
>;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| document | DocumentNode | The parsed GraphQL document containing the subscription operation. |
| rootValue? | unknown | Initial root value passed to the subscription resolver. |
| contextValue? | unknown | Application 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. |
| Type | Description |
|---|---|
Promise<
ExecutionResult | AsyncIterable<unknown, any, any>
> | The source event stream, or an execution result containing subscription errors. |
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; // => trueCategory: 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;
};
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| varDefNodes | readonly VariableDefinitionNode[] | The variable definition AST nodes to coerce. |
| inputs | { readonly [variable: string]: unknown } | The runtime variable values keyed by variable name. |
| options? | GetVariableValuesOptions | Optional variable coercion options, including error limits. |
| Type | Description |
|---|---|
| {
errors: ReadonlyArray<GraphQLError>;
coerced?: never;
}
| {
coerced: { [variable: string]: unknown };
errors?: never;
} | Coerced variable values, or request errors. |
// 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 } }// 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 };
| Name | Type | Description |
|---|---|---|
| def | GraphQLField<unknown, unknown> | GraphQLDirective | The field or directive definition whose arguments should be coerced. |
| node | FieldNode | DirectiveNode | The AST node to inspect. |
| variableValues? | Maybe<ObjMap<unknown>> | The runtime variable values keyed by variable name. |
| Type | Description |
|---|---|
{ [argument: string]: unknown } | Coerced argument values keyed by argument name. |
// 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 }// 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 errorgetDirectiveValues()
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;
| Name | Type | Description |
|---|---|---|
| directiveDef | GraphQLDirective | The directive definition whose arguments should be coerced. |
| node | DirectiveValuesNode | The AST node to inspect. |
| variableValues? | Maybe<ObjMap<unknown>> | The runtime variable values keyed by variable name. |
| Type | Description |
|---|---|
{ [argument: string]: unknown } | undefined | Coerced directive argument values keyed by argument name. |
// 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 }// 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: [] }); // => undefinedCategory: Paths
Functions:
responsePathAsArray()
Functions
responsePathAsArray()
Given a Path, return an Array of the path keys.
Signature:
responsePathAsArray(
path: Maybe<
Readonly<Path>
>,
): (string | number)[];
| Name | Type | Description |
|---|---|---|
| path | Maybe<Readonly<Path>> | The linked response path to flatten. |
| Type | Description |
|---|---|
(string | number)[] | An array of response path keys from root to leaf. |
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); // => []