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
Functions:
execute()executeRootSelectionSet()executeSync()executeSubscriptionEvent()subscribe()createSourceEventStream()validateExecutionArgs()validateSubscriptionArgs()mapSourceToResponseEvent()
Constants:
defaultTypeResolverdefaultFieldResolver
Types:
ValidatedExecutionArgsValidatedSubscriptionArgsExecutionResultFormattedExecutionResultRootSelectionSetExecutorExecutionArgsAsyncWorkFinishedInfoExecutionHooks
Classes
AbortedGraphQLExecutionError
Error thrown when GraphQL execution is aborted.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TResult | Result value type. |
Constructor
Creates an error for an aborted GraphQL execution.
Signature:
new AbortedGraphQLExecutionError(
reason: unknown,
result: PromiseOrValue<TResult>,
);
| Name | Type | Description |
|---|---|---|
| reason | unknown | Abort reason used as the error cause. |
| result | PromiseOrValue<TResult> | Partial execution result available when execution stopped. |
Members
| Name | Type | Description |
|---|---|---|
| abortedResult | PromiseOrValue<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>;
| 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. |
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>;
| Name | Type | Description |
|---|---|---|
| validatedExecutionArgs | ValidatedExecutionArgs | Validated execution arguments. |
| Type | Description |
|---|---|
PromiseOrValue<ExecutionResult> | Execution result for the operation root selection set. |
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;
| Name | Type | Description |
|---|---|---|
| args | ExecutionArgs | The arguments used to perform the operation. |
| Type | Description |
|---|---|
ExecutionResult | Completed execution output for a synchronous operation. |
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>;
| Name | Type | Description |
|---|---|---|
| validatedExecutionArgs | ValidatedSubscriptionArgs | Validated subscription execution arguments. |
| Type | Description |
|---|---|
PromiseOrValue<ExecutionResult> | Execution result for the subscription event. |
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>
>;
| Name | Type | Description |
|---|---|---|
| args | ExecutionArgs | Execution arguments for the subscription operation. |
| Type | Description |
|---|---|
PromiseOrValue<
ExecutionResult | AsyncGenerator<ExecutionResult, void, void>
> | A response stream for a valid subscription, or an execution result containing 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' } }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
>;
| Name | Type | Description |
|---|---|---|
| validatedExecutionArgs | ValidatedSubscriptionArgs | Validated subscription execution arguments. |
| Type | Description |
|---|---|
PromiseOrValue<
AsyncIterable<unknown, any, any> | ExecutionResult
> | A source event stream, or an execution result containing errors. |
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; // => truevalidateExecutionArgs()
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[];
| Name | Type | Description |
|---|---|---|
| args | ExecutionArgs | Execution arguments to validate. |
| Type | Description |
|---|---|
ValidatedExecutionArgs | readonly GraphQLError[] | Validated execution arguments, or validation errors. |
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; // => truevalidateSubscriptionArgs()
Validates execution arguments for a subscription operation.
Signature:
validateSubscriptionArgs(
args: ExecutionArgs,
): ValidatedSubscriptionArgs | readonly GraphQLError[];
| Name | Type | Description |
|---|---|---|
| args | ExecutionArgs | Execution arguments to validate. |
| Type | Description |
|---|---|
ValidatedSubscriptionArgs | readonly GraphQLError[] | Validated subscription execution arguments, or validation errors. |
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>;
| Name | Type | Default | Description |
|---|---|---|---|
| validatedExecutionArgs | ValidatedSubscriptionArgs | Validated subscription execution arguments. | |
| sourceEventStream | AsyncIterable<unknown> | Source event stream returned by the subscription resolver. | |
| rootSelectionSetExecutor | RootSelectionSetExecutor | executeSubscriptionEvent | Function used to execute each source event. |
| Type | Description |
|---|---|
AsyncGenerator<ExecutionResult, void, void> | A response stream of execution results. |
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.
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
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
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | Schema used for execution. |
| fragmentDefinitions | ObjMap<FragmentDefinitionNode> | Fragment definitions keyed by fragment name. |
| fragments | ObjMap<FragmentDetails> | Fragment details keyed by fragment name. |
| rootValue | unknown | Root value passed to the operation. |
| contextValue | unknown | Application context value passed to every resolver. |
| operation | OperationDefinitionNode | Operation definition selected for execution. |
| variableValues | VariableValues | Operation variable values with source metadata and coerced runtime values. |
| fieldResolver | GraphQLFieldResolver<any, any> | Resolver used for fields without an explicit resolver. |
| typeResolver | GraphQLTypeResolver<any, any> | Resolver used for abstract types without an explicit type resolver. |
| subscribeFieldResolver | GraphQLFieldResolver<any, any> | Resolver used for subscription fields without an explicit subscribe resolver. |
| hideSuggestions | boolean | Whether suggestion text should be omitted from execution errors. |
| errorPropagation | boolean | Whether execution should use error propagation. |
| externalAbortSignal | any | External signal that may abort execution. |
| enableEarlyExecution | boolean | Whether incremental execution may begin eligible work early. |
| hooks | ExecutionHooks | undefined | Execution hooks supplied by the caller. |
ValidatedSubscriptionArgs
Interface. Validated execution arguments for a subscription operation.
interface ValidatedSubscriptionArgs extends ValidatedExecutionArgs
| Name | Type | Description |
|---|---|---|
| operation | SubscriptionOperationDefinitionNode | Subscription operation definition selected for execution. |
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 | Additional non-standard metadata included in the execution 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 | Additional 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.
| 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. |
| hideSuggestions? | Maybe<boolean> | Whether suggestion text should be omitted from request errors. |
| abortSignal? | any | AbortSignal 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? | object | Additional execution options. |
AsyncWorkFinishedInfo
Interface. Information passed to hooks after asynchronous execution work has finished.
| Name | Type | Description |
|---|---|---|
| validatedExecutionArgs | ValidatedExecutionArgs | Validated execution arguments for the operation that finished async work. |
ExecutionHooks
Interface. Optional hooks invoked during GraphQL execution.
| Name | Type | Description |
|---|---|---|
| asyncWorkFinished? | (info: AsyncWorkFinishedInfo) => void | Called after all tracked asynchronous execution work has settled. |
Category: Incremental Execution
Functions:
experimentalExecuteIncrementally()experimentalExecuteRootSelectionSet()
Types:
ExperimentalIncrementalExecutionResultsFormattedExperimentalIncrementalExecutionResultsInitialIncrementalExecutionResultFormattedInitialIncrementalExecutionResultSubsequentIncrementalExecutionResultFormattedSubsequentIncrementalExecutionResultIncrementalDeferResultFormattedIncrementalDeferResultIncrementalStreamResultFormattedIncrementalStreamResultIncrementalResultFormattedIncrementalResult
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>;
| Name | Type | Description |
|---|---|---|
| args | ExecutionArgs | Execution arguments for the GraphQL operation. |
| Type | Description |
|---|---|
PromiseOrValue<ExecutionResult | ExperimentalIncrementalExecutionResults> | A single execution result or incremental execution results. |
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>;
| Name | Type | Description |
|---|---|---|
| validatedExecutionArgs | ValidatedExecutionArgs | Validated execution arguments. |
| Type | Description |
|---|---|
PromiseOrValue<ExecutionResult | ExperimentalIncrementalExecutionResults> | A single execution result or incremental execution results. |
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.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TInitialData | ObjMap<unknown> | Shape of the initial result data payload. | |
| TDeferredData | ObjMap<unknown> | Shape of deferred fragment data payloads. | |
| TStreamItem | unknown | Shape of streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of extensions payloads. |
| Name | Type | Description |
|---|---|---|
| initialResult | InitialIncrementalExecutionResult<TInitialData, TExtensions> | Initial execution result delivered before subsequent incremental payloads. |
| subsequentResults | AsyncGenerator<
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.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TInitial | ObjMap<unknown> | Shape of the formatted initial result data payload. | |
| TDeferredData | ObjMap<unknown> | Shape of formatted deferred fragment data payloads. | |
| TStreamItem | unknown | Shape of formatted streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of formatted extensions payloads. |
| Name | Type | Description |
|---|---|---|
| initialResult | FormattedInitialIncrementalExecutionResult<TInitial, TExtensions> | Formatted initial execution result. |
| subsequentResults | AsyncGenerator<
FormattedSubsequentIncrementalExecutionResult<
TDeferredData,
TStreamItem,
TExtensions
>,
void,
void
> | Async stream of formatted incremental payloads. |
InitialIncrementalExecutionResult
Interface. Initial execution result for an operation that produced incremental payloads.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TData | ObjMap<unknown> | Shape of the initial data payload. | |
| TExtensions | ObjMap<unknown> | Shape of the extensions payload. |
interface InitialIncrementalExecutionResult<
TData = ObjMap<unknown>,
TExtensions = ObjMap<unknown>,
> extends ExecutionResult<TData, TExtensions>
| Name | Type | Description |
|---|---|---|
| data | TData | Data produced by the initial execution payload. |
| pending | readonly PendingResult[] | Incremental payloads that are still pending after the initial result. |
| hasNext | true | Indicates that subsequent incremental payloads will follow. |
| extensions? | TExtensions | Additional non-standard metadata included in the initial result. |
FormattedInitialIncrementalExecutionResult
Interface. JSON-serializable form of an initial incremental execution result.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TInitialData | ObjMap<unknown> | Shape of the formatted initial data payload. | |
| TExtensions | ObjMap<unknown> | Shape of the formatted extensions payload. |
interface FormattedInitialIncrementalExecutionResult<
TInitialData = ObjMap<unknown>,
TExtensions = ObjMap<unknown>,
> extends FormattedExecutionResult<TInitialData, TExtensions>
| Name | Type | Description |
|---|---|---|
| data | TInitialData | Formatted data produced by the initial execution payload. |
| pending | readonly PendingResult[] | Formatted list of incremental payloads still pending after the initial result. |
| hasNext | boolean | Indicates whether subsequent incremental payloads will follow. |
| extensions? | TExtensions | Additional non-standard metadata included in the formatted initial result. |
SubsequentIncrementalExecutionResult
Interface. Subsequent payload produced by incremental execution.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of deferred fragment data payloads. | |
| TStreamItem | unknown | Shape of streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of the extensions payload. |
| Name | Type | Description |
|---|---|---|
| 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. |
| hasNext | boolean | Indicates whether more incremental payloads will follow. |
| extensions? | TExtensions | Additional non-standard metadata included in this payload. |
FormattedSubsequentIncrementalExecutionResult
Interface. JSON-serializable form of a subsequent incremental execution payload.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of formatted deferred fragment data payloads. | |
| TStreamItem | unknown | Shape of formatted streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of formatted extensions payloads. |
| Name | Type | Description |
|---|---|---|
| hasNext | boolean | Indicates 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? | TExtensions | Additional non-standard metadata included in this formatted payload. |
IncrementalDeferResult
Interface. Incremental payload produced by a deferred fragment.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of deferred fragment data. | |
| TExtensions | ObjMap<unknown> | Shape of extensions payloads. |
| Name | Type | Description |
|---|---|---|
| id | string | Identifier 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. |
| data | TDeferredData | Data produced by the deferred fragment. |
| extensions? | TExtensions | Additional non-standard metadata included in this payload. |
FormattedIncrementalDeferResult
Interface. JSON-serializable form of a deferred fragment payload.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of formatted deferred fragment data. | |
| TExtensions | ObjMap<unknown> | Shape of formatted extensions payloads. |
| Name | Type | Description |
|---|---|---|
| errors? | readonly GraphQLFormattedError[] | Formatted errors raised while executing the deferred fragment. |
| data | TDeferredData | Formatted data produced by the deferred fragment. |
| id | string | Identifier matching this payload to a pending deferred fragment. |
| subPath? | readonly (string | number)[] | Path from the deferred fragment location to this payload. |
| extensions? | TExtensions | Additional non-standard metadata included in this formatted payload. |
IncrementalStreamResult
Interface. Incremental payload produced by a streamed list field.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TStreamItem | unknown | Shape of streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of extensions payloads. |
| Name | Type | Description |
|---|---|---|
| id | string | Identifier 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. |
| items | readonly TStreamItem[] | Streamed list items delivered by this payload. |
| extensions? | TExtensions | Additional non-standard metadata included in this payload. |
FormattedIncrementalStreamResult
Interface. JSON-serializable form of a streamed list payload.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TStreamItem | unknown[] | Shape of formatted streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of formatted extensions payloads. |
| Name | Type | Description |
|---|---|---|
| errors? | readonly GraphQLFormattedError[] | Formatted errors raised while producing streamed items. |
| items | readonly TStreamItem[] | Formatted streamed list items delivered by this payload. |
| id | string | Identifier matching this payload to a pending stream. |
| subPath? | readonly (string | number)[] | Path from the streamed field location to these items. |
| extensions? | TExtensions | Additional non-standard metadata included in this formatted payload. |
IncrementalResult
Type alias. Deferred fragment or streamed list payload produced by incremental execution.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of deferred fragment data. | |
| TStreamItem | unknown | Shape of streamed list items. | |
| TExtensions | ObjMap<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.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of formatted deferred fragment data. | |
| TStreamItem | unknown | Shape of formatted streamed list items. | |
| TExtensions | ObjMap<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()legacyExecuteRootSelectionSet()
Types:
LegacyExperimentalIncrementalExecutionResultsLegacyInitialIncrementalExecutionResultLegacySubsequentIncrementalExecutionResultLegacyIncrementalResultLegacyIncrementalDeferResultLegacyIncrementalStreamResultFormattedLegacyExperimentalIncrementalExecutionResultsFormattedLegacyInitialIncrementalExecutionResultFormattedLegacySubsequentIncrementalExecutionResultFormattedLegacyIncrementalResultFormattedLegacyIncrementalDeferResultFormattedLegacyIncrementalStreamResult
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>;
| Name | Type | Description |
|---|---|---|
| args | ExecutionArgs | Execution arguments for the GraphQL operation. |
| Type | Description |
|---|---|
PromiseOrValue<ExecutionResult | LegacyExperimentalIncrementalExecutionResults> | A single execution result or legacy incremental execution results. |
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 }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 }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>;
| Name | Type | Description |
|---|---|---|
| validatedExecutionArgs | ValidatedExecutionArgs | Validated execution arguments. |
| Type | Description |
|---|---|
PromiseOrValue<ExecutionResult | LegacyExperimentalIncrementalExecutionResults> | A single execution result or legacy incremental execution results. |
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.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TInitialData | ObjMap<unknown> | Shape of the initial result data payload. | |
| TDeferredData | ObjMap<unknown> | Shape of deferred fragment data payloads. | |
| TStreamItem | unknown | Shape of streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of extensions payloads. |
| Name | Type | Description |
|---|---|---|
| initialResult | LegacyInitialIncrementalExecutionResult<TInitialData, TExtensions> | Initial execution result delivered before subsequent legacy incremental payloads. |
| subsequentResults | AsyncGenerator<
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.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TInitialData | ObjMap<unknown> | Shape of the initial data payload. | |
| TExtensions | ObjMap<unknown> | Shape of the extensions payload. |
interface LegacyInitialIncrementalExecutionResult<
TInitialData = ObjMap<unknown>,
TExtensions = ObjMap<unknown>,
> extends ExecutionResult<TInitialData, TExtensions>
| Name | Type | Description |
|---|---|---|
| data | TInitialData | Data produced by the initial execution payload. |
| hasNext | true | Indicates that subsequent legacy incremental payloads will follow. |
| extensions? | TExtensions | Additional 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.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of deferred fragment data payloads. | |
| TStreamItem | unknown | Shape of streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of the extensions payload. |
| Name | Type | Description |
|---|---|---|
| incremental? | readonly LegacyIncrementalResult<
TDeferredData,
TStreamItem,
TExtensions
>[] | Deferred or streamed payloads delivered by this response. |
| hasNext | boolean | Indicates whether more legacy incremental payloads will follow. |
| extensions? | TExtensions | Additional non-standard metadata included in this payload. |
LegacyIncrementalResult
Type alias. Deferred fragment or streamed list payload produced by legacy incremental execution.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of deferred fragment data. | |
| TStreamItem | unknown | Shape of streamed list items. | |
| TExtensions | ObjMap<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.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of deferred fragment data. | |
| TExtensions | ObjMap<unknown> | Shape of extensions payloads. |
interface LegacyIncrementalDeferResult<
TDeferredData = ObjMap<unknown>,
TExtensions = ObjMap<unknown>,
> extends ExecutionResult<TDeferredData, TExtensions>
| Name | Type | Description |
|---|---|---|
| path | readonly (string | number)[] | Response path to the deferred fragment payload. |
| label? | string | Label from the @defer directive. |
LegacyIncrementalStreamResult
Interface. Legacy incremental payload produced by a streamed list field.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TStreamItem | unknown | Shape of streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of extensions payloads. |
| Name | Type | Description |
|---|---|---|
| errors? | readonly GraphQLError[] | Errors raised while producing streamed items. |
| items | readonly TStreamItem[] | null | Streamed list items delivered by this payload. |
| path | readonly (string | number)[] | Response path to the first streamed list item in this payload. |
| label? | string | Label from the @stream directive. |
| extensions? | TExtensions | Additional non-standard metadata included in this payload. |
FormattedLegacyExperimentalIncrementalExecutionResults
Interface. JSON-serializable form of legacy incremental execution results.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TInitialData | ObjMap<unknown> | Shape of the formatted initial result data payload. | |
| TDeferredData | ObjMap<unknown> | Shape of formatted deferred fragment data payloads. | |
| TStreamItem | unknown | Shape of formatted streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of formatted extensions payloads. |
| Name | Type | Description |
|---|---|---|
| initialResult | FormattedLegacyInitialIncrementalExecutionResult<TInitialData, TExtensions> | Formatted initial execution result. |
| subsequentResults | AsyncGenerator<
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.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TInitialData | ObjMap<unknown> | Shape of the formatted initial data payload. | |
| TExtensions | ObjMap<unknown> | Shape of the formatted extensions payload. |
interface FormattedLegacyInitialIncrementalExecutionResult<
TInitialData = ObjMap<unknown>,
TExtensions = ObjMap<unknown>,
> extends FormattedExecutionResult<TInitialData, TExtensions>
| Name | Type | Description |
|---|---|---|
| data | TInitialData | Formatted data produced by the initial execution payload. |
| hasNext | true | Indicates that subsequent legacy incremental payloads will follow. |
| extensions? | TExtensions | Additional non-standard metadata included in the formatted initial result. |
FormattedLegacySubsequentIncrementalExecutionResult
Interface. JSON-serializable form of a legacy subsequent incremental execution payload.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of formatted deferred fragment data payloads. | |
| TStreamItem | unknown | Shape of formatted streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of formatted extensions payloads. |
| Name | Type | Description |
|---|---|---|
| incremental? | readonly FormattedLegacyIncrementalResult<
TDeferredData,
TStreamItem,
TExtensions
>[] | Formatted deferred or streamed payloads delivered by this response. |
| hasNext | boolean | Indicates whether more legacy incremental payloads will follow. |
| extensions? | TExtensions | Additional non-standard metadata included in this formatted payload. |
FormattedLegacyIncrementalResult
Type alias. JSON-serializable deferred fragment or streamed list payload produced by legacy incremental execution.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of formatted deferred fragment data. | |
| TStreamItem | unknown | Shape of formatted streamed list items. | |
| TExtensions | ObjMap<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.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TDeferredData | ObjMap<unknown> | Shape of formatted deferred fragment data. | |
| TExtensions | ObjMap<unknown> | Shape of formatted extensions payloads. |
interface FormattedLegacyIncrementalDeferResult<
TDeferredData = ObjMap<unknown>,
TExtensions = ObjMap<unknown>,
> extends FormattedExecutionResult<TDeferredData, TExtensions>
| Name | Type | Description |
|---|---|---|
| path | readonly (string | number)[] | Response path to the formatted deferred fragment payload. |
| label? | string | Label from the @defer directive. |
FormattedLegacyIncrementalStreamResult
Interface. JSON-serializable form of a legacy streamed list payload.
| Name | Constraint | Default | Description |
|---|---|---|---|
| TStreamItem | unknown | Shape of formatted streamed list items. | |
| TExtensions | ObjMap<unknown> | Shape of formatted extensions payloads. |
| Name | Type | Description |
|---|---|---|
| errors? | readonly GraphQLFormattedError[] | Formatted errors raised while producing streamed items. |
| items | readonly TStreamItem[] | null | Formatted streamed list items delivered by this payload. |
| path | readonly (string | number)[] | Response path to the first streamed list item in this formatted payload. |
| label? | string | Label from the @stream directive. |
| extensions? | TExtensions | Additional 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;
};
| 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? | { maxErrors?: number; hideSuggestions?: boolean } | Optional configuration for this operation. |
| Type | Description |
|---|---|
| { variableValues: VariableValues; errors?: never }
| {
errors: ReadonlyArray<GraphQLError>;
variableValues?: never;
} | Coerced variable values with source metadata, or request errors. |
// 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 }// 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>;
| Name | Type | Description |
|---|---|---|
| def | GraphQLField<unknown, unknown> | GraphQLDirective | Field or directive definition that declares the arguments. |
| node | FieldNode | DirectiveNode | Field 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. |
| Type | Description |
|---|---|
ObjMap<unknown> | A map of coerced argument values. |
// 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 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 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 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;
| Name | Type | Description |
|---|---|---|
| directiveDef | GraphQLDirective | Directive 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. |
| Type | Description |
|---|---|
ObjMap<unknown> | undefined | A map of coerced directive argument values, or undefined when absent. |
// 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 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: [] }); // => undefinedTypes
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.
| Name | Type | Description |
|---|---|---|
| sources | ReadOnlyObjMap<{
signature: GraphQLVariableSignature;
value?: unknown;
}> | Source metadata for each variable value keyed by variable name. |
| coerced | ReadOnlyObjMap<unknown> | Coerced runtime variable values keyed by variable name. |
Category: 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); // => []