🎉 Explore GraphQLConf 2026 • May 19-21 • Fremont, CA • View the schedule
v17 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

Classes

AbortedGraphQLExecutionError

Error thrown when GraphQL execution is aborted.


Type Parameters
NameConstraintDefaultDescription
TResultResult value type.

Constructor

Creates an error for an aborted GraphQL execution.

Signature:

new AbortedGraphQLExecutionError(
  reason: unknown,
  result: PromiseOrValue<TResult>,
);

Arguments
NameTypeDescription
reasonunknownAbort reason used as the error cause.
resultPromiseOrValue<TResult>Partial execution result available when execution stopped.

Members
NameTypeDescription
abortedResultPromiseOrValue<TResult>Partial execution result available when execution was aborted.

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.

This function does not support incremental delivery (@defer and @stream). Use experimentalExecuteIncrementally to execute operations with incremental delivery enabled.

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
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!' } }

executeRootSelectionSet()

Implements the “Executing operations” section of the spec.

Returns a Promise that will eventually resolve to the data described by The “Response” section of the GraphQL specification.

If errors are encountered while executing a GraphQL field, only that field and its descendants will be omitted, and sibling fields will still be executed. An execution which encounters errors will still result in a resolved Promise.

Errors from sub-fields of a NonNull type may propagate to the top level, at which point we still log the error and null the parent field, which in this case is the entire response.

Signature:

executeRootSelectionSet(
  validatedExecutionArgs: ValidatedExecutionArgs,
): PromiseOrValue<ExecutionResult>;

Arguments
NameTypeDescription
validatedExecutionArgsValidatedExecutionArgsValidated execution arguments.

Returns
TypeDescription
PromiseOrValue<ExecutionResult>Execution result for the operation root selection set.

Example
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { executeRootSelectionSet, validateExecutionArgs } from 'graphql/execution';
 
const schema = buildSchema('type Query { greeting: String }');
const validatedArgs = validateExecutionArgs({
  schema,
  document: parse('{ greeting }'),
  rootValue: { greeting: 'Hello' },
});
 
assert('schema' in validatedArgs);
 
const result = await executeRootSelectionSet(validatedArgs);
result; // => { data: { greeting: 'Hello' } }

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
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { executeSync } from 'graphql/execution';
 
const schema = buildSchema('type Query { greeting: String }');
 
const result = executeSync({
  schema,
  document: parse('{ greeting }'),
  rootValue: { greeting: 'Hello' },
});
 
result; // => { data: { greeting: 'Hello' } }

executeSubscriptionEvent()

Executes a subscription operation once for a single source event.

Signature:

executeSubscriptionEvent(
  validatedExecutionArgs: ValidatedSubscriptionArgs,
): PromiseOrValue<ExecutionResult>;

Arguments
NameTypeDescription
validatedExecutionArgsValidatedSubscriptionArgsValidated subscription execution arguments.

Returns
TypeDescription
PromiseOrValue<ExecutionResult>Execution result for the subscription event.

Example
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { executeSubscriptionEvent, validateSubscriptionArgs } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    noop: String
  }
 
  type Subscription {
    greeting: String
  }
`);
const validatedArgs = validateSubscriptionArgs({
  schema,
  document: parse('subscription { greeting }'),
  rootValue: { greeting: 'Hello' },
});
 
assert('schema' in validatedArgs);
 
const result = await executeSubscriptionEvent(validatedArgs);
result; // => { data: { greeting: 'Hello' } }

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.

This function does not support incremental delivery (@defer and @stream). If an operation which would defer or stream data is executed with this function, a field error will be raised at the location of the @defer or @stream directive.

Accepts an object with named arguments.

Signature:

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

Arguments
NameTypeDescription
argsExecutionArgsExecution arguments for the subscription operation.

Returns
TypeDescription
PromiseOrValue< ExecutionResult | AsyncGenerator<ExecutionResult, void, void> >A response stream for a valid subscription, or an execution result containing 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' } }

createSourceEventStream()

Implements the “CreateSourceEventStream” algorithm described in the GraphQL specification, resolving the subscription source event stream for a previously validated subscription request.

Returns a Promise that resolves to either an AsyncIterable (if successful) or an ExecutionResult (error). The promise will be rejected if the validated execution arguments 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(
  validatedExecutionArgs: ValidatedSubscriptionArgs,
): PromiseOrValue<
  AsyncIterable<unknown, any, any> | ExecutionResult
>;

Arguments
NameTypeDescription
validatedExecutionArgsValidatedSubscriptionArgsValidated subscription execution arguments.

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

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

validateExecutionArgs()

Constructs a ExecutionContext object from the arguments passed to execute, which we will pass throughout the other execution methods.

Throws a GraphQLError if a valid execution context cannot be created.

TODO: consider no longer exporting this function

Signature:

validateExecutionArgs(
  args: ExecutionArgs,
): ValidatedExecutionArgs | readonly GraphQLError[];

Arguments
NameTypeDescription
argsExecutionArgsExecution arguments to validate.

Returns
TypeDescription
ValidatedExecutionArgs | readonly GraphQLError[]Validated execution arguments, or validation errors.

Example
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { validateExecutionArgs } from 'graphql/execution';
 
const schema = buildSchema(`
  interface Named {
    name: String!
  }
 
  type User implements Named {
    name: String!
  }
 
  type Query {
    viewer: Named
  }
`);
const abortController = new AbortController();
const validatedArgs = validateExecutionArgs({
  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;
  },
  hideSuggestions: true,
  abortSignal: abortController.signal,
  enableEarlyExecution: true,
  hooks: {
    asyncWorkFinished: () => {},
  },
  options: { maxCoercionErrors: 1 },
});
 
assert('operation' in validatedArgs);
 
validatedArgs.operation.name?.value; // => 'Viewer'
validatedArgs.hideSuggestions; // => true

validateSubscriptionArgs()

Validates execution arguments for a subscription operation.

Signature:

validateSubscriptionArgs(
  args: ExecutionArgs,
): ValidatedSubscriptionArgs | readonly GraphQLError[];

Arguments
NameTypeDescription
argsExecutionArgsExecution arguments to validate.

Returns
TypeDescription
ValidatedSubscriptionArgs | readonly GraphQLError[]Validated subscription execution arguments, or validation errors.

Example
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { validateSubscriptionArgs } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    noop: String
  }
 
  type Subscription {
    greeting: String
  }
`);
const validatedArgs = validateSubscriptionArgs({
  schema,
  document: parse('subscription { greeting }'),
});
 
assert('operation' in validatedArgs);
 
validatedArgs.operation.operation; // => 'subscription'

mapSourceToResponseEvent()

Implements the “MapSourceToResponseEvent” algorithm described in the GraphQL specification, mapping each event from a subscription source event stream to an ExecutionResult in the response stream.

Signature:

mapSourceToResponseEvent(
  validatedExecutionArgs: ValidatedSubscriptionArgs,
  sourceEventStream: AsyncIterable<unknown>,
  rootSelectionSetExecutor: RootSelectionSetExecutor = executeSubscriptionEvent,
): AsyncGenerator<ExecutionResult, void, void>;

Arguments
NameTypeDefaultDescription
validatedExecutionArgsValidatedSubscriptionArgsValidated subscription execution arguments.
sourceEventStreamAsyncIterable<unknown>Source event stream returned by the subscription resolver.
rootSelectionSetExecutorRootSelectionSetExecutorexecuteSubscriptionEventFunction used to execute each source event.

Returns
TypeDescription
AsyncGenerator<ExecutionResult, void, void>A response stream of execution results.

Example
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { mapSourceToResponseEvent, validateSubscriptionArgs } from 'graphql/execution';
 
async function* events() {
  yield { greeting: 'Hello' };
}
 
const schema = buildSchema(`
  type Query {
    noop: String
  }
 
  type Subscription {
    greeting: String
  }
`);
const validatedArgs = validateSubscriptionArgs({
  schema,
  document: parse('subscription { greeting }'),
});
 
assert('schema' in validatedArgs);
 
const responseStream = mapSourceToResponseEvent(validatedArgs, events());
const firstPayload = await responseStream.next();
 
firstPayload.value; // => { data: { greeting: 'Hello' } }

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

ValidatedExecutionArgs

Interface. Data that must be available at all points during query execution.

Namely, schema of the type system that is currently executing, and the fragments defined in the query document


Members
NameTypeDescription
schemaGraphQLSchemaSchema used for execution.
fragmentDefinitionsObjMap<FragmentDefinitionNode>Fragment definitions keyed by fragment name.
fragmentsObjMap<FragmentDetails>Fragment details keyed by fragment name.
rootValueunknownRoot value passed to the operation.
contextValueunknownApplication context value passed to every resolver.
operationOperationDefinitionNodeOperation definition selected for execution.
variableValuesVariableValuesOperation variable values with source metadata and coerced runtime values.
fieldResolverGraphQLFieldResolver<any, any>Resolver used for fields without an explicit resolver.
typeResolverGraphQLTypeResolver<any, any>Resolver used for abstract types without an explicit type resolver.
subscribeFieldResolverGraphQLFieldResolver<any, any>Resolver used for subscription fields without an explicit subscribe resolver.
hideSuggestionsbooleanWhether suggestion text should be omitted from execution errors.
errorPropagationbooleanWhether execution should use error propagation.
externalAbortSignalanyExternal signal that may abort execution.
enableEarlyExecutionbooleanWhether incremental execution may begin eligible work early.
hooksExecutionHooks | undefinedExecution hooks supplied by the caller.

ValidatedSubscriptionArgs

Interface. Validated execution arguments for a subscription operation.

interface ValidatedSubscriptionArgs extends ValidatedExecutionArgs

Members
NameTypeDescription
operationSubscriptionOperationDefinitionNodeSubscription operation definition selected for execution.

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?TExtensionsAdditional non-standard metadata included in the execution 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?TExtensionsAdditional non-standard metadata included in the formatted result.

RootSelectionSetExecutor

Type alias. Function used to execute a validated root selection set for a subscription event.

type RootSelectionSetExecutor = (
  validatedExecutionArgs: ValidatedSubscriptionArgs,
) => PromiseOrValue<ExecutionResult>;

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.
hideSuggestions?Maybe<boolean>Whether suggestion text should be omitted from request errors.
abortSignal?anyAbortSignal used to cancel execution.
enableEarlyExecution?Maybe<boolean>Whether incremental execution may begin eligible work early.
hooks?Maybe<ExecutionHooks>Execution hooks invoked during this operation.
options?objectAdditional execution options.

AsyncWorkFinishedInfo

Interface. Information passed to hooks after asynchronous execution work has finished.


Members
NameTypeDescription
validatedExecutionArgsValidatedExecutionArgsValidated execution arguments for the operation that finished async work.

ExecutionHooks

Interface. Optional hooks invoked during GraphQL execution.


Members
NameTypeDescription
asyncWorkFinished?(info: AsyncWorkFinishedInfo) => voidCalled after all tracked asynchronous execution work has settled.

Category: Incremental Execution

Functions

experimentalExecuteIncrementally()

Implements the “Executing requests” section of the GraphQL specification, including @defer and @stream as proposed in https://github.com/graphql/graphql-spec/pull/742

This function returns either a single ExecutionResult, or an ExperimentalIncrementalExecutionResults object containing an initialResult and a stream of subsequentResults.

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

Signature:

experimentalExecuteIncrementally(
  args: ExecutionArgs,
): PromiseOrValue<ExecutionResult | ExperimentalIncrementalExecutionResults>;

Arguments
NameTypeDescription
argsExecutionArgsExecution arguments for the GraphQL operation.

Returns
TypeDescription
PromiseOrValue<ExecutionResult | ExperimentalIncrementalExecutionResults>A single execution result or incremental execution results.

Example
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { experimentalExecuteIncrementally } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    greeting: String
  }
`);
 
const result = await experimentalExecuteIncrementally({
  schema,
  document: parse('{ greeting }'),
  rootValue: { greeting: 'Hello' },
});
 
result; // => { data: { greeting: 'Hello' } }

experimentalExecuteRootSelectionSet()

Executes the operation root selection set with incremental delivery enabled.

Signature:

experimentalExecuteRootSelectionSet(
  validatedExecutionArgs: ValidatedExecutionArgs,
): PromiseOrValue<ExecutionResult | ExperimentalIncrementalExecutionResults>;

Arguments
NameTypeDescription
validatedExecutionArgsValidatedExecutionArgsValidated execution arguments.

Returns
TypeDescription
PromiseOrValue<ExecutionResult | ExperimentalIncrementalExecutionResults>A single execution result or incremental execution results.

Example
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import {
  experimentalExecuteRootSelectionSet,
  validateExecutionArgs,
} from 'graphql/execution';
 
const schema = buildSchema('type Query { greeting: String }');
const validatedArgs = validateExecutionArgs({
  schema,
  document: parse('{ greeting }'),
  rootValue: { greeting: 'Hello' },
});
 
assert('schema' in validatedArgs);
 
const result = await experimentalExecuteRootSelectionSet(validatedArgs);
result; // => { data: { greeting: 'Hello' } }

Types

ExperimentalIncrementalExecutionResults

Interface. Results for an operation that produced incremental payloads.


Type Parameters
NameConstraintDefaultDescription
TInitialDataObjMap<unknown>Shape of the initial result data payload.
TDeferredDataObjMap<unknown>Shape of deferred fragment data payloads.
TStreamItemunknownShape of streamed list items.
TExtensionsObjMap<unknown>Shape of extensions payloads.

Members
NameTypeDescription
initialResultInitialIncrementalExecutionResult<TInitialData, TExtensions>Initial execution result delivered before subsequent incremental payloads.
subsequentResultsAsyncGenerator< SubsequentIncrementalExecutionResult< TDeferredData, TStreamItem, TExtensions >, void, void >Async stream of incremental payloads delivered after the initial result.

FormattedExperimentalIncrementalExecutionResults

Interface. JSON-serializable form of incremental execution results.


Type Parameters
NameConstraintDefaultDescription
TInitialObjMap<unknown>Shape of the formatted initial result data payload.
TDeferredDataObjMap<unknown>Shape of formatted deferred fragment data payloads.
TStreamItemunknownShape of formatted streamed list items.
TExtensionsObjMap<unknown>Shape of formatted extensions payloads.

Members
NameTypeDescription
initialResultFormattedInitialIncrementalExecutionResult<TInitial, TExtensions>Formatted initial execution result.
subsequentResultsAsyncGenerator< FormattedSubsequentIncrementalExecutionResult< TDeferredData, TStreamItem, TExtensions >, void, void >Async stream of formatted incremental payloads.

InitialIncrementalExecutionResult

Interface. Initial execution result for an operation that produced incremental payloads.


Type Parameters
NameConstraintDefaultDescription
TDataObjMap<unknown>Shape of the initial data payload.
TExtensionsObjMap<unknown>Shape of the extensions payload.
interface InitialIncrementalExecutionResult<
  TData = ObjMap<unknown>,
  TExtensions = ObjMap<unknown>,
> extends ExecutionResult<TData, TExtensions>

Members
NameTypeDescription
dataTDataData produced by the initial execution payload.
pendingreadonly PendingResult[]Incremental payloads that are still pending after the initial result.
hasNexttrueIndicates that subsequent incremental payloads will follow.
extensions?TExtensionsAdditional non-standard metadata included in the initial result.

FormattedInitialIncrementalExecutionResult

Interface. JSON-serializable form of an initial incremental execution result.


Type Parameters
NameConstraintDefaultDescription
TInitialDataObjMap<unknown>Shape of the formatted initial data payload.
TExtensionsObjMap<unknown>Shape of the formatted extensions payload.
interface FormattedInitialIncrementalExecutionResult<
  TInitialData = ObjMap<unknown>,
  TExtensions = ObjMap<unknown>,
> extends FormattedExecutionResult<TInitialData, TExtensions>

Members
NameTypeDescription
dataTInitialDataFormatted data produced by the initial execution payload.
pendingreadonly PendingResult[]Formatted list of incremental payloads still pending after the initial result.
hasNextbooleanIndicates whether subsequent incremental payloads will follow.
extensions?TExtensionsAdditional non-standard metadata included in the formatted initial result.

SubsequentIncrementalExecutionResult

Interface. Subsequent payload produced by incremental execution.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of deferred fragment data payloads.
TStreamItemunknownShape of streamed list items.
TExtensionsObjMap<unknown>Shape of the extensions payload.

Members
NameTypeDescription
pending?readonly PendingResult[]Incremental payloads that became pending with this response.
incremental?readonly IncrementalResult< TDeferredData, TStreamItem, TExtensions >[]Deferred or streamed payloads delivered by this response.
completed?readonly CompletedResult[]Incremental payloads that completed with this response.
hasNextbooleanIndicates whether more incremental payloads will follow.
extensions?TExtensionsAdditional non-standard metadata included in this payload.

FormattedSubsequentIncrementalExecutionResult

Interface. JSON-serializable form of a subsequent incremental execution payload.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of formatted deferred fragment data payloads.
TStreamItemunknownShape of formatted streamed list items.
TExtensionsObjMap<unknown>Shape of formatted extensions payloads.

Members
NameTypeDescription
hasNextbooleanIndicates whether more incremental payloads will follow.
pending?readonly PendingResult[]Formatted incremental payloads that became pending with this response.
incremental?readonly FormattedIncrementalResult< TDeferredData, TStreamItem, TExtensions >[]Formatted deferred or streamed payloads delivered by this response.
completed?readonly FormattedCompletedResult[]Formatted incremental payloads that completed with this response.
extensions?TExtensionsAdditional non-standard metadata included in this formatted payload.

IncrementalDeferResult

Interface. Incremental payload produced by a deferred fragment.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of deferred fragment data.
TExtensionsObjMap<unknown>Shape of extensions payloads.

Members
NameTypeDescription
idstringIdentifier matching this payload to a pending deferred fragment.
subPath?readonly (string | number)[]Path from the deferred fragment location to this payload.
errors?readonly GraphQLError[]Errors raised while executing the deferred fragment.
dataTDeferredDataData produced by the deferred fragment.
extensions?TExtensionsAdditional non-standard metadata included in this payload.

FormattedIncrementalDeferResult

Interface. JSON-serializable form of a deferred fragment payload.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of formatted deferred fragment data.
TExtensionsObjMap<unknown>Shape of formatted extensions payloads.

Members
NameTypeDescription
errors?readonly GraphQLFormattedError[]Formatted errors raised while executing the deferred fragment.
dataTDeferredDataFormatted data produced by the deferred fragment.
idstringIdentifier matching this payload to a pending deferred fragment.
subPath?readonly (string | number)[]Path from the deferred fragment location to this payload.
extensions?TExtensionsAdditional non-standard metadata included in this formatted payload.

IncrementalStreamResult

Interface. Incremental payload produced by a streamed list field.


Type Parameters
NameConstraintDefaultDescription
TStreamItemunknownShape of streamed list items.
TExtensionsObjMap<unknown>Shape of extensions payloads.

Members
NameTypeDescription
idstringIdentifier matching this payload to a pending stream.
subPath?readonly (string | number)[]Path from the streamed field location to these items.
errors?readonly GraphQLError[]Errors raised while producing streamed items.
itemsreadonly TStreamItem[]Streamed list items delivered by this payload.
extensions?TExtensionsAdditional non-standard metadata included in this payload.

FormattedIncrementalStreamResult

Interface. JSON-serializable form of a streamed list payload.


Type Parameters
NameConstraintDefaultDescription
TStreamItemunknown[]Shape of formatted streamed list items.
TExtensionsObjMap<unknown>Shape of formatted extensions payloads.

Members
NameTypeDescription
errors?readonly GraphQLFormattedError[]Formatted errors raised while producing streamed items.
itemsreadonly TStreamItem[]Formatted streamed list items delivered by this payload.
idstringIdentifier matching this payload to a pending stream.
subPath?readonly (string | number)[]Path from the streamed field location to these items.
extensions?TExtensionsAdditional non-standard metadata included in this formatted payload.

IncrementalResult

Type alias. Deferred fragment or streamed list payload produced by incremental execution.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of deferred fragment data.
TStreamItemunknownShape of streamed list items.
TExtensionsObjMap<unknown>Shape of extensions payloads.
type IncrementalResult<
  TDeferredData = ObjMap<unknown>,
  TStreamItem = unknown,
  TExtensions = ObjMap<unknown>,
> =
  | IncrementalDeferResult<TDeferredData, TExtensions>
  | IncrementalStreamResult<TStreamItem, TExtensions>;

FormattedIncrementalResult

Type alias. JSON-serializable deferred fragment or streamed list payload.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of formatted deferred fragment data.
TStreamItemunknownShape of formatted streamed list items.
TExtensionsObjMap<unknown>Shape of formatted extensions payloads.
type FormattedIncrementalResult<
  TDeferredData = ObjMap<unknown>,
  TStreamItem = unknown,
  TExtensions = ObjMap<unknown>,
> =
  | FormattedIncrementalDeferResult<TDeferredData, TExtensions>
  | FormattedIncrementalStreamResult<TStreamItem, TExtensions>;

Category: Legacy Incremental Execution

Functions

legacyExecuteIncrementally()

Executes a GraphQL operation with support for @defer and @stream using the legacy incremental delivery payload format.

Prefer experimentalExecuteIncrementally for the current incremental delivery format. In the legacy format, each subsequent incremental payload identifies its location with path and optional label fields. The current format instead tracks pending work by id and reports completion through completed entries.

Signature:

legacyExecuteIncrementally(
  args: ExecutionArgs,
): PromiseOrValue<ExecutionResult | LegacyExperimentalIncrementalExecutionResults>;

Arguments
NameTypeDescription
argsExecutionArgsExecution arguments for the GraphQL operation.

Returns
TypeDescription
PromiseOrValue<ExecutionResult | LegacyExperimentalIncrementalExecutionResults>A single execution result or legacy incremental execution results.

Example 1
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { legacyExecuteIncrementally } from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    hero: Hero
  }
 
  type Hero {
    id: ID!
    name: String!
  }
`);
 
const result = await legacyExecuteIncrementally({
  schema,
  document: parse('{ hero { id ... @defer(label: "HeroName") { name } } }'),
  rootValue: { hero: { id: '1', name: 'Luke' } },
});
 
assert('initialResult' in result);
 
result.initialResult; // => { data: { hero: { id: '1' } }, hasNext: true }
 
const deferred = await result.subsequentResults.next();
deferred.value; // => { incremental: [ { data: { name: 'Luke' }, path: ['hero'], label: 'HeroName' } ], hasNext: false }

Example 2

Compare the legacy payload format with the current incremental delivery format returned by experimentalExecuteIncrementally.

import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import {
  experimentalExecuteIncrementally,
  legacyExecuteIncrementally,
} from 'graphql/execution';
 
const schema = buildSchema(`
  type Query {
    hero: Hero
  }
 
  type Hero {
    id: ID!
    name: String!
  }
`);
const document = parse('{ hero { id ... @defer { name } } }');
const rootValue = { hero: { id: '1', name: 'Luke' } };
 
const experimental = await experimentalExecuteIncrementally({
  schema,
  document,
  rootValue,
});
const legacy = await legacyExecuteIncrementally({
  schema,
  document,
  rootValue,
});
 
assert('initialResult' in experimental);
assert('initialResult' in legacy);
 
experimental.initialResult; // => { data: { hero: { id: '1' } }, pending: [ { id: '0', path: ['hero'] } ], hasNext: true }
legacy.initialResult; // => { data: { hero: { id: '1' } }, hasNext: true }
 
const experimentalDeferred = await experimental.subsequentResults.next();
experimentalDeferred.value; // => { incremental: [{ data: { name: 'Luke' }, id: '0' }], completed: [{ id: '0' }], hasNext: false }
 
const legacyDeferred = await legacy.subsequentResults.next();
legacyDeferred.value; // => { incremental: [ { data: { name: 'Luke' }, path: ['hero'] } ], hasNext: false }

Example 3

Compare streamed list payloads in the legacy and current incremental delivery formats.

import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import {
  experimentalExecuteIncrementally,
  legacyExecuteIncrementally,
} from 'graphql/execution';
 
const schema = buildSchema('type Query { colors: [String] }');
const document = parse('{ colors @stream(initialCount: 1) }');
const rootValue = { colors: ['red', 'green', 'blue'] };
 
const experimental = await experimentalExecuteIncrementally({
  schema,
  document,
  rootValue,
});
const legacy = await legacyExecuteIncrementally({
  schema,
  document,
  rootValue,
});
 
assert('initialResult' in experimental);
assert('initialResult' in legacy);
 
experimental.initialResult; // => { data: { colors: ['red'] }, pending: [ { id: '0', path: ['colors'] } ], hasNext: true }
legacy.initialResult; // => { data: { colors: ['red'] }, hasNext: true }
 
const experimentalStream = await experimental.subsequentResults.next();
experimentalStream.value; // => { incremental: [ { items: ['green', 'blue'], id: '0' } ], completed: [{ id: '0' }], hasNext: false }
 
const legacyStream = await legacy.subsequentResults.next();
legacyStream.value; // => { incremental: [ { items: ['green', 'blue'], path: ['colors', 1] } ], hasNext: false }

legacyExecuteRootSelectionSet()

Executes a validated operation root selection set with support for @defer and @stream using the legacy incremental delivery payload format.

Signature:

legacyExecuteRootSelectionSet(
  validatedExecutionArgs: ValidatedExecutionArgs,
): PromiseOrValue<ExecutionResult | LegacyExperimentalIncrementalExecutionResults>;

Arguments
NameTypeDescription
validatedExecutionArgsValidatedExecutionArgsValidated execution arguments.

Returns
TypeDescription
PromiseOrValue<ExecutionResult | LegacyExperimentalIncrementalExecutionResults>A single execution result or legacy incremental execution results.

Example
import assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import {
  legacyExecuteRootSelectionSet,
  validateExecutionArgs,
} from 'graphql/execution';
 
const schema = buildSchema('type Query { greeting: String }');
const validatedArgs = validateExecutionArgs({
  schema,
  document: parse('{ greeting }'),
  rootValue: { greeting: 'Hello' },
});
 
assert('schema' in validatedArgs);
 
const result = await legacyExecuteRootSelectionSet(validatedArgs);
result; // => { data: { greeting: 'Hello' } }

Types

LegacyExperimentalIncrementalExecutionResults

Interface. Results for an operation that produced legacy incremental payloads.


Type Parameters
NameConstraintDefaultDescription
TInitialDataObjMap<unknown>Shape of the initial result data payload.
TDeferredDataObjMap<unknown>Shape of deferred fragment data payloads.
TStreamItemunknownShape of streamed list items.
TExtensionsObjMap<unknown>Shape of extensions payloads.

Members
NameTypeDescription
initialResultLegacyInitialIncrementalExecutionResult<TInitialData, TExtensions>Initial execution result delivered before subsequent legacy incremental payloads.
subsequentResultsAsyncGenerator< LegacySubsequentIncrementalExecutionResult< TDeferredData, TStreamItem, TExtensions >, void, void >Async stream of legacy incremental payloads delivered after the initial result.

LegacyInitialIncrementalExecutionResult

Interface. Initial execution result for an operation that produced legacy incremental payloads.

Unlike InitialIncrementalExecutionResult, the legacy initial result does not include a pending list. Subsequent payloads identify their location directly with path and optional label fields.


Type Parameters
NameConstraintDefaultDescription
TInitialDataObjMap<unknown>Shape of the initial data payload.
TExtensionsObjMap<unknown>Shape of the extensions payload.
interface LegacyInitialIncrementalExecutionResult<
  TInitialData = ObjMap<unknown>,
  TExtensions = ObjMap<unknown>,
> extends ExecutionResult<TInitialData, TExtensions>

Members
NameTypeDescription
dataTInitialDataData produced by the initial execution payload.
hasNexttrueIndicates that subsequent legacy incremental payloads will follow.
extensions?TExtensionsAdditional non-standard metadata included in the initial result.

LegacySubsequentIncrementalExecutionResult

Interface. Subsequent payload produced by legacy incremental execution.

Legacy subsequent payloads may contain deferred fragment data, streamed list items, or only hasNext: false to complete the response stream.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of deferred fragment data payloads.
TStreamItemunknownShape of streamed list items.
TExtensionsObjMap<unknown>Shape of the extensions payload.

Members
NameTypeDescription
incremental?readonly LegacyIncrementalResult< TDeferredData, TStreamItem, TExtensions >[]Deferred or streamed payloads delivered by this response.
hasNextbooleanIndicates whether more legacy incremental payloads will follow.
extensions?TExtensionsAdditional non-standard metadata included in this payload.

LegacyIncrementalResult

Type alias. Deferred fragment or streamed list payload produced by legacy incremental execution.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of deferred fragment data.
TStreamItemunknownShape of streamed list items.
TExtensionsObjMap<unknown>Shape of extensions payloads.
type LegacyIncrementalResult<
  TDeferredData = ObjMap<unknown>,
  TStreamItem = unknown,
  TExtensions = ObjMap<unknown>,
> =
  | LegacyIncrementalDeferResult<TDeferredData, TExtensions>
  | LegacyIncrementalStreamResult<TStreamItem, TExtensions>;

LegacyIncrementalDeferResult

Interface. Legacy incremental payload produced by a deferred fragment.

The payload location is identified directly by path and optional label instead of by an id from a pending entry.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of deferred fragment data.
TExtensionsObjMap<unknown>Shape of extensions payloads.
interface LegacyIncrementalDeferResult<
  TDeferredData = ObjMap<unknown>,
  TExtensions = ObjMap<unknown>,
> extends ExecutionResult<TDeferredData, TExtensions>

Members
NameTypeDescription
pathreadonly (string | number)[]Response path to the deferred fragment payload.
label?stringLabel from the @defer directive.

LegacyIncrementalStreamResult

Interface. Legacy incremental payload produced by a streamed list field.


Type Parameters
NameConstraintDefaultDescription
TStreamItemunknownShape of streamed list items.
TExtensionsObjMap<unknown>Shape of extensions payloads.

Members
NameTypeDescription
errors?readonly GraphQLError[]Errors raised while producing streamed items.
itemsreadonly TStreamItem[] | nullStreamed list items delivered by this payload.
pathreadonly (string | number)[]Response path to the first streamed list item in this payload.
label?stringLabel from the @stream directive.
extensions?TExtensionsAdditional non-standard metadata included in this payload.

FormattedLegacyExperimentalIncrementalExecutionResults

Interface. JSON-serializable form of legacy incremental execution results.


Type Parameters
NameConstraintDefaultDescription
TInitialDataObjMap<unknown>Shape of the formatted initial result data payload.
TDeferredDataObjMap<unknown>Shape of formatted deferred fragment data payloads.
TStreamItemunknownShape of formatted streamed list items.
TExtensionsObjMap<unknown>Shape of formatted extensions payloads.

Members
NameTypeDescription
initialResultFormattedLegacyInitialIncrementalExecutionResult<TInitialData, TExtensions>Formatted initial execution result.
subsequentResultsAsyncGenerator< FormattedLegacySubsequentIncrementalExecutionResult< TDeferredData, TStreamItem, TExtensions >, void, void >Async stream of formatted legacy incremental payloads.

FormattedLegacyInitialIncrementalExecutionResult

Interface. JSON-serializable form of a legacy initial incremental execution result.


Type Parameters
NameConstraintDefaultDescription
TInitialDataObjMap<unknown>Shape of the formatted initial data payload.
TExtensionsObjMap<unknown>Shape of the formatted extensions payload.
interface FormattedLegacyInitialIncrementalExecutionResult<
  TInitialData = ObjMap<unknown>,
  TExtensions = ObjMap<unknown>,
> extends FormattedExecutionResult<TInitialData, TExtensions>

Members
NameTypeDescription
dataTInitialDataFormatted data produced by the initial execution payload.
hasNexttrueIndicates that subsequent legacy incremental payloads will follow.
extensions?TExtensionsAdditional non-standard metadata included in the formatted initial result.

FormattedLegacySubsequentIncrementalExecutionResult

Interface. JSON-serializable form of a legacy subsequent incremental execution payload.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of formatted deferred fragment data payloads.
TStreamItemunknownShape of formatted streamed list items.
TExtensionsObjMap<unknown>Shape of formatted extensions payloads.

Members
NameTypeDescription
incremental?readonly FormattedLegacyIncrementalResult< TDeferredData, TStreamItem, TExtensions >[]Formatted deferred or streamed payloads delivered by this response.
hasNextbooleanIndicates whether more legacy incremental payloads will follow.
extensions?TExtensionsAdditional non-standard metadata included in this formatted payload.

FormattedLegacyIncrementalResult

Type alias. JSON-serializable deferred fragment or streamed list payload produced by legacy incremental execution.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of formatted deferred fragment data.
TStreamItemunknownShape of formatted streamed list items.
TExtensionsObjMap<unknown>Shape of formatted extensions payloads.
type FormattedLegacyIncrementalResult<
  TDeferredData = ObjMap<unknown>,
  TStreamItem = unknown,
  TExtensions = ObjMap<unknown>,
> =
  | FormattedLegacyIncrementalDeferResult<TDeferredData, TExtensions>
  | FormattedLegacyIncrementalStreamResult<TStreamItem, TExtensions>;

FormattedLegacyIncrementalDeferResult

Interface. JSON-serializable form of a legacy deferred fragment payload.


Type Parameters
NameConstraintDefaultDescription
TDeferredDataObjMap<unknown>Shape of formatted deferred fragment data.
TExtensionsObjMap<unknown>Shape of formatted extensions payloads.
interface FormattedLegacyIncrementalDeferResult<
  TDeferredData = ObjMap<unknown>,
  TExtensions = ObjMap<unknown>,
> extends FormattedExecutionResult<TDeferredData, TExtensions>

Members
NameTypeDescription
pathreadonly (string | number)[]Response path to the formatted deferred fragment payload.
label?stringLabel from the @defer directive.

FormattedLegacyIncrementalStreamResult

Interface. JSON-serializable form of a legacy streamed list payload.


Type Parameters
NameConstraintDefaultDescription
TStreamItemunknownShape of formatted streamed list items.
TExtensionsObjMap<unknown>Shape of formatted extensions payloads.

Members
NameTypeDescription
errors?readonly GraphQLFormattedError[]Formatted errors raised while producing streamed items.
itemsreadonly TStreamItem[] | nullFormatted streamed list items delivered by this payload.
pathreadonly (string | number)[]Response path to the first streamed list item in this formatted payload.
label?stringLabel from the @stream directive.
extensions?TExtensionsAdditional non-standard metadata included in this formatted payload.

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 maps use null prototypes to avoid collisions with Object prototype properties.

Signature:

getVariableValues(
  schema: GraphQLSchema,
  varDefNodes: readonly VariableDefinitionNode[],
  inputs: { readonly [variable: string]: unknown },
  options?: {
    maxErrors?: number;
    hideSuggestions?: boolean;
  },
):
  | {
      variableValues: VariableValues;
      errors?: never;
    }
  | {
      errors: ReadonlyArray<GraphQLError>;
      variableValues?: 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?{ maxErrors?: number; hideSuggestions?: boolean }Optional configuration for this operation.

Returns
TypeDescription
| { variableValues: VariableValues; errors?: never } | { errors: ReadonlyArray<GraphQLError>; variableValues?: never; }Coerced variable values with source metadata, or request errors.

Example 1
// Coerce provided variables and apply operation defaults.
import assert from 'node:assert';
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' },
);
 
assert('variableValues' in result);
 
result.variableValues.coerced; // => { stars: 5, limit: 10 }

Example 2
// This variant uses maxErrors to cap reported coercion errors.
import assert from 'node:assert';
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 },
);
 
assert('errors' in result);
 
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 uses a null prototype to avoid collisions with JavaScript’s own property names.

Signature:

getArgumentValues(
  def:
    | GraphQLField<unknown, unknown>
    | GraphQLDirective,
  node: FieldNode | DirectiveNode,
  variableValues?: Maybe<VariableValues>,
  fragmentVariableValues?: Maybe<FragmentVariableValues>,
  hideSuggestions?: Maybe<boolean>,
): ObjMap<unknown>;

Arguments
NameTypeDescription
defGraphQLField<unknown, unknown> | GraphQLDirectiveField or directive definition that declares the arguments.
nodeFieldNode | DirectiveNodeField or directive AST node supplying argument literals.
variableValues?Maybe<VariableValues>Operation variable values returned by getVariableValues.
fragmentVariableValues?Maybe<FragmentVariableValues>Fragment variable values for the current fragment scope.
hideSuggestions?Maybe<boolean>Whether suggestion text should be omitted from errors.

Returns
TypeDescription
ObjMap<unknown>A map of coerced argument values.

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 assert from 'node:assert';
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { getArgumentValues, getVariableValues } 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 operation = document.definitions[0];
const fieldNode = document.definitions[0].selectionSet.selections[0];
const variables = getVariableValues(
  schema,
  operation.variableDefinitions,
  { stars: '5' },
);
 
assert('variableValues' in variables);
 
getArgumentValues(fieldDef, fieldNode, variables.variableValues); // => { 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 uses a null prototype to avoid collisions with JavaScript’s own property names.

Signature:

getDirectiveValues(
  directiveDef: GraphQLDirective,
  node: {
    directives?: readonly DirectiveNode[];
  },
  variableValues?: Maybe<VariableValues>,
  fragmentVariableValues?: Maybe<FragmentVariableValues>,
  hideSuggestions?: Maybe<boolean>,
): ObjMap<unknown> | undefined;

Arguments
NameTypeDescription
directiveDefGraphQLDirectiveDirective definition to read argument definitions from.
node{ directives?: readonly DirectiveNode[] }AST node that may contain directives.
variableValues?Maybe<VariableValues>Operation variable values returned by getVariableValues.
fragmentVariableValues?Maybe<FragmentVariableValues>Fragment variable values for the current fragment scope.
hideSuggestions?Maybe<boolean>Whether suggestion text should be omitted from errors.

Returns
TypeDescription
ObjMap<unknown> | undefinedA map of coerced directive argument values, or undefined when absent.

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 assert from 'node:assert';
import { parse } from 'graphql/language';
import { GraphQLIncludeDirective } from 'graphql/type';
import { buildSchema } from 'graphql/utilities';
import { getDirectiveValues, getVariableValues } from 'graphql/execution';
 
const schema = buildSchema('type Query { name: String }');
const document = parse('query ($includeName: Boolean!) { name @include(if: $includeName) }');
const operation = document.definitions[0];
const fieldNode = document.definitions[0].selectionSet.selections[0];
const variables = getVariableValues(
  schema,
  operation.variableDefinitions,
  { includeName: false },
);
 
assert('variableValues' in variables);
 
getDirectiveValues(GraphQLIncludeDirective, fieldNode, variables.variableValues); // => { if: false }
getDirectiveValues(GraphQLIncludeDirective, { directives: [] }); // => undefined

Types

VariableValues

Interface. Coerced variable values prepared for execution.

The coerced map contains runtime values keyed by variable name. The sources map records whether each value came from request input, an operation default, or a fragment-variable default so utilities can preserve defaults when replacing variables in literals.


Members
NameTypeDescription
sourcesReadOnlyObjMap<{ signature: GraphQLVariableSignature; value?: unknown; }>Source metadata for each variable value keyed by variable name.
coercedReadOnlyObjMap<unknown>Coerced runtime variable values keyed by variable name.

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); // => []