v17 APIgraphql/execution

graphql/execution

The graphql/execution entry point executes already parsed and usually already validated GraphQL operations. It also contains subscription helpers, argument and variable coercion helpers.

import { execute, subscribe } from 'graphql/execution';

The same exports are also available from the root graphql entry point.

execute() is the stable single-result executor for queries and mutations. subscribe() and createSourceEventStream() provide the subscription pipeline.

Contents

Core Execution Exports

ExportKindDescription
execute() Changed in v17FunctionExecutes a query or mutation and returns one ExecutionResult or a promise for one.
executeSync() Changed in v17FunctionExecutes synchronously and throws if execution becomes asynchronous or incremental.
defaultFieldResolverFunctionDefault field resolver. It reads a same-named property or calls a same-named method on the source value.
defaultTypeResolverFunctionDefault abstract type resolver. It uses __typename first, then isTypeOf checks.
responsePathAsArray()FunctionConverts an execution response path linked list into an array.
import { execute, parse } from 'graphql';
 
const document = parse('{ viewer { name } }');
const result = await execute({
  schema,
  document,
  contextValue: { currentUser },
});

Subscription Exports

The legacy graphql/subscription subpath and SubscriptionArgs type were removed in v17. Use subscribe() and createSourceEventStream() from graphql or graphql/execution.

ExportKindDescription
subscribe() Changed in v17FunctionRuns the full subscription pipeline and returns an async iterator of ExecutionResult values or one error result.
createSourceEventStream() Changed in v17FunctionCreates the source event stream for a subscription operation.
const streamOrResult = await subscribe({
  schema,
  document,
  contextValue,
});
 
if (Symbol.asyncIterator in Object(streamOrResult)) {
  for await (const result of streamOrResult) {
    send(result);
  }
}

Argument, Variable, and Directive Helpers

ExportKindDescription
getVariableValues() Changed in v17FunctionCoerces operation variable values and returns either { variableValues } or { errors }.
getArgumentValues() Changed in v17FunctionCoerces argument values for a field, directive, or fragment argument definition.
getDirectiveValues()FunctionCoerces values for a directive usage and returns undefined when the directive is absent.

Pipeline Split Helpers

v17 exposes validated argument objects so hosts can split the execution pipeline without re-implementing GraphQL.js internals. Most applications should use execute() and subscribe() directly; these helpers are for framework authors and advanced hosts.

ExportKindDescription
validateExecutionArgs() New in v17FunctionValidates ExecutionArgs — checks the schema, selects the operation, coerces variables, and fills in defaults. Returns ValidatedExecutionArgs on success or an array of GraphQLError values on failure.
validateSubscriptionArgs() New in v17FunctionValidates ExecutionArgs for a subscription. Returns ValidatedSubscriptionArgs on success or an array of errors.
executeRootSelectionSet() New in v17FunctionExecutes the root selection set given a pre-validated ValidatedExecutionArgs. The stable, single-result root executor used internally by execute().
experimentalExecuteRootSelectionSet() New in v17FunctionExecutes the root selection set with incremental delivery support. Used internally by experimentalExecuteIncrementally().
executeSubscriptionEvent() New in v17FunctionExecutes one subscription event given pre-validated ValidatedSubscriptionArgs. Used internally by subscribe() and mapSourceToResponseEvent().
mapSourceToResponseEvent() New in v17FunctionMaps a source event stream to a GraphQL response event stream. Used internally by subscribe() and available to advanced hosts that manage their own event streams.
import {
  validateExecutionArgs,
  executeRootSelectionSet,
  validateSubscriptionArgs,
  mapSourceToResponseEvent,
} from 'graphql/execution';
 
// Split query execution into validation and execution phases:
const validated = validateExecutionArgs({ schema, document, variableValues });
 
const result =
  'schema' in validated
    ? await executeRootSelectionSet(validated)
    : { errors: validated };
 
// Manage a subscription stream manually:
const validatedSub = validateSubscriptionArgs({ schema, document });
if (!('schema' in validatedSub)) return { errors: validatedSub };
 
const sourceStream = await createSourceEventStream(validatedSub);
const responseStream = mapSourceToResponseEvent(validatedSub, sourceStream);
 
for await (const event of responseStream) {
  send(event);
}

See Advanced Execution Pipelines for full usage patterns.

Incremental Delivery Exports

The experimental incremental delivery API supports @defer and @stream. See Defer and Stream for usage.

ExportKindDescription
experimentalExecuteIncrementally() New in v17FunctionExecutes a query or mutation with incremental delivery support. Returns ExperimentalIncrementalExecutionResults for operations that use @defer or @stream, or a plain ExecutionResult otherwise.
ExperimentalIncrementalExecutionResults New in v17TypeResult when incremental delivery is active: { initialResult, subsequentResults }.
InitialIncrementalExecutionResult New in v17TypeFirst incremental result, carrying optional data, errors, and hasNext: true.
SubsequentIncrementalExecutionResult New in v17TypeSubsequent incremental payload with incremental chunks and hasNext.
IncrementalDeferResult New in v17TypeIncremental payload for one deferred fragment.
IncrementalStreamResult New in v17TypeIncremental payload for one streamed list item.
IncrementalResult New in v17TypeUnion of IncrementalDeferResult and IncrementalStreamResult.
FormattedExperimentalIncrementalExecutionResults New in v17TypeJSON-serializable form of ExperimentalIncrementalExecutionResults.
FormattedInitialIncrementalExecutionResult New in v17TypeJSON-serializable form of InitialIncrementalExecutionResult.
FormattedSubsequentIncrementalExecutionResult New in v17TypeJSON-serializable form of SubsequentIncrementalExecutionResult.
FormattedIncrementalDeferResult New in v17TypeJSON-serializable form of IncrementalDeferResult.
FormattedIncrementalStreamResult New in v17TypeJSON-serializable form of IncrementalStreamResult.
FormattedIncrementalResult New in v17TypeJSON-serializable form of IncrementalResult.
import { experimentalExecuteIncrementally } from 'graphql/execution';
 
const result = await experimentalExecuteIncrementally({ schema, document });
 
if ('initialResult' in result) {
  send(result.initialResult);
  for await (const chunk of result.subsequentResults) {
    send(chunk);
  }
} else {
  send(result);
}

Execution Hooks and Abort

ExportKindDescription
AbortedGraphQLExecutionError New in v17ClassThrown when execution is aborted via an AbortSignal. Extends Error. Caught internally during execution and converted to a field error.
ExecutionHooks New in v17TypeObject with optional lifecycle hook callbacks (beforeField, afterField, onError) passed to execute() via ExecutionArgs.hooks.
AsyncWorkFinishedInfo New in v17TypeObject passed to the afterField hook once asynchronous resolution completes.
import type { ExecutionHooks } from 'graphql/execution';
 
const hooks: ExecutionHooks = {
  beforeField(info) {
    return { startTime: performance.now() };
  },
  afterField(info, context) {
    const elapsed = performance.now() - context.startTime;
    recordFieldTiming(info.fieldName, elapsed);
  },
};
 
await execute({ schema, document, hooks });

See Execution Hooks for full usage and the hook type signatures.

Result and Argument Types

ExportDescription
ExecutionArgs Changed in v17Arguments accepted by execute(), subscribe(), validateExecutionArgs(), validateSubscriptionArgs(), and related helpers. v17 adds hooks, abortSignal, and hideSuggestions.
ExecutionResultStandard GraphQL execution result with optional data, errors, and extensions.
FormattedExecutionResultJSON-serializable execution result shape.
ValidatedExecutionArgs New in v17Pre-validated execution arguments returned by validateExecutionArgs(). Consumed by executeRootSelectionSet() and experimentalExecuteRootSelectionSet().
ValidatedSubscriptionArgs New in v17Pre-validated subscription arguments returned by validateSubscriptionArgs(). Consumed by executeSubscriptionEvent() and mapSourceToResponseEvent().
RootSelectionSetExecutor New in v17Function type for the root selection set executor hook. Accepts ValidatedExecutionArgs and returns a promise for ExecutionResult.