The root graphql package re-exports the public GraphQL.js API from its
submodules and provides the high-level request pipeline helpers defined in
this module.
You can import public exports from GraphQL.js modules through the root
graphql package or through their module-specific entry point. For example,
these two references resolve to the same parse function:
import { parse } from 'graphql';
import { parse } from 'graphql/language';Use the root package when you want a single import surface, or use submodules
such as graphql/language, graphql/type, graphql/execution, and
graphql/utilities when you want module-focused imports. This module also
defines root-only APIs, such as request pipeline helpers and version
metadata, that do not belong to a narrower submodule.
For documentation purposes, these exports are grouped into the following categories:
Category: Development Mode
Functions:
enableDevMode()isDevModeEnabled()
Functions
enableDevMode()
Enables GraphQL.js development mode checks for this module instance.
Production entry points leave development mode disabled by default. Call this before constructing schemas or executing requests when additional development diagnostics should run.
Signature:
enableDevMode(): void;
import { enableDevMode, isDevModeEnabled } from 'graphql/devMode';
isDevModeEnabled(); // => false
enableDevMode();
isDevModeEnabled(); // => trueisDevModeEnabled()
Returns whether GraphQL.js development mode has been enabled for this module instance.
Signature:
isDevModeEnabled(): boolean;
| Type | Description |
|---|---|
boolean | True when development mode is enabled. |
import { enableDevMode, isDevModeEnabled } from 'graphql/devMode';
enableDevMode();
isDevModeEnabled(); // => trueCategory: Diagnostics
Types:
GraphQLParseContextGraphQLValidateContextGraphQLExecuteContextGraphQLExecuteRootSelectionSetContextGraphQLExecuteVariableCoercionContextGraphQLSubscribeContextGraphQLResolveContextGraphQLChannelContextByNameGraphQLChannels
Types
GraphQLParseContext
Interface. Context published on the sync-only graphql:parse channel.
| Name | Type | Description |
|---|---|---|
| source | string | Source | Source text or source object passed to the parser. |
| error? | unknown | Error thrown while parsing, when parsing fails. |
| result? | DocumentNode | Parsed document, when parsing succeeds. |
GraphQLValidateContext
Interface. Context published on the sync-only graphql:validate channel.
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | Schema used for validation. |
| document | DocumentNode | Parsed document being validated. |
| error? | unknown | Error thrown while validating, when validation fails abruptly. |
| result? | readonly GraphQLError[] | Validation errors returned by validation. |
GraphQLExecuteContext
Interface. Context published on graphql:execute.
Returned results may contain GraphQL errors collected during execution.
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | Schema used for execution. |
| document | DocumentNode | Parsed document being executed. |
| rawVariableValues | Maybe<{
readonly [variable: string]: unknown;
}> | Raw variable values provided by the caller before coercion. |
| operationName | string | undefined | Selected operation name, if one is available. |
| operationType | OperationTypeNode | undefined | Selected operation type, if one is available. |
| error? | unknown | Error thrown or rejected while executing, when execution fails abruptly. |
| result? | ExecutionResult | ExperimentalIncrementalExecutionResults | Execution result returned by execution, including GraphQL errors. |
GraphQLExecuteRootSelectionSetContext
Interface. Context published on graphql:execute:rootSelectionSet.
Returned results may contain GraphQL errors collected during execution.
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | Schema used for execution. |
| document | DocumentNode | Parsed document being executed. |
| operation | OperationDefinitionNode | Operation definition selected for execution. |
| rawVariableValues | Maybe<{
readonly [variable: string]: unknown;
}> | Raw variable values provided by the caller before coercion. |
| operationName | string | undefined | Selected operation name, if one is available. |
| operationType | OperationTypeNode | Selected operation type. |
| error? | unknown | Error thrown or rejected while executing the root selection set. |
| result? | ExecutionResult | ExperimentalIncrementalExecutionResults | Execution result returned from the root selection set, including GraphQL errors. |
GraphQLExecuteVariableCoercionContext
Interface. Context published on graphql:execute:variableCoercion.
Coercion runs synchronously while execution arguments are validated, so only
the start/end (and, on an abrupt throw, error) lifecycle fires.
Ordinary variable coercion failures are returned on result.errors; when
execution is invoked through APIs such as execute() or subscribe(), they
surface as GraphQL result errors rather than as the tracing error
lifecycle event.
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | Schema used for variable coercion. |
| document | DocumentNode | Parsed document being executed. |
| operation | OperationDefinitionNode | Operation definition whose variables are being coerced. |
| rawVariableValues | Maybe<{
readonly [variable: string]: unknown;
}> | Raw variable values provided by the caller before coercion. |
| operationName | string | undefined | Selected operation name, if one is available. |
| operationType | OperationTypeNode | Selected operation type. |
| error? | unknown | Error thrown while coercing variables, when coercion fails abruptly. |
| result? | | { variableValues: VariableValues }
| { errors: readonly GraphQLError[] } | Coerced variable values or coercion errors returned by coercion. |
GraphQLSubscribeContext
Interface. Context published on graphql:subscribe.
Subscription source resolver errors and invalid source stream results are
returned on result as ExecutionResult errors; they do not publish the
error lifecycle event unless subscription setup fails abruptly before
GraphQL can form a result.
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | Schema used for subscription execution. |
| document | DocumentNode | Parsed subscription document. |
| rawVariableValues | Maybe<{
readonly [variable: string]: unknown;
}> | Raw variable values provided by the caller before coercion. |
| operationName | string | undefined | Selected operation name, if one is available. |
| operationType | OperationTypeNode | undefined | Selected operation type, if one is available. |
| error? | unknown | Error thrown or rejected while subscribing, when setup fails abruptly. |
| result? | | ExecutionResult
| AsyncGenerator<ExecutionResult, void, void> | Subscription response stream, or an ExecutionResult containing GraphQL errors. |
GraphQLResolveContext
Interface. Context published on graphql:resolve.
Resolver throws and rejections publish the error lifecycle event here.
The same failure may also be formatted into the enclosing execution or
subscription result.
| Name | Type | Description |
|---|---|---|
| fieldName | string | Field name being resolved. |
| alias | string | Response alias for the field being resolved. |
| parentType | string | Parent type name for the field being resolved. |
| fieldType | string | Return type string for the field being resolved. |
| args | ObjMap<unknown> | Argument values passed to the resolver. |
| isDefaultResolver | boolean | Whether the field is using the default resolver. |
| fieldPath | string | Response path for the field being resolved. |
| error? | unknown | Error thrown or rejected by the resolver, when resolution fails. |
| result? | unknown | Value returned by the resolver, when resolution succeeds. |
GraphQLChannelContextByName
Interface. Mapping from tracing channel name to the context type published on it.
| Name | Type | Description |
|---|---|---|
| graphql:parse | GraphQLParseContext | Context published on graphql:parse. |
| graphql:validate | GraphQLValidateContext | Context published on graphql:validate. |
| graphql:execute | GraphQLExecuteContext | Context published on graphql:execute. |
| graphql:execute:variableCoercion | GraphQLExecuteVariableCoercionContext | Context published on graphql:execute:variableCoercion. |
| graphql:execute:rootSelectionSet | GraphQLExecuteRootSelectionSetContext | Context published on graphql:execute:rootSelectionSet. |
| graphql:subscribe | GraphQLSubscribeContext | Context published on graphql:subscribe. |
| graphql:resolve | GraphQLResolveContext | Context published on graphql:resolve. |
GraphQLChannels
Interface. The collection of tracing channels GraphQL.js emits on. Application
performance monitoring (APM) tools subscribe to these by name on their own
node:diagnostics_channel import; both paths land on the same channel
instance because tracingChannel(name) is cached by name.
| Name | Type | Description |
|---|---|---|
| execute | MinimalTracingChannel<GraphQLExecuteContext> | Tracing channel for graphql:execute. |
| executeVariableCoercion | MinimalTracingChannel<GraphQLExecuteVariableCoercionContext> | Tracing channel for graphql:execute:variableCoercion. |
| executeRootSelectionSet | MinimalTracingChannel<GraphQLExecuteRootSelectionSetContext> | Tracing channel for graphql:execute:rootSelectionSet. |
| parse | MinimalTracingChannel<GraphQLParseContext> | Tracing channel for graphql:parse. |
| validate | MinimalTracingChannel<GraphQLValidateContext> | Tracing channel for graphql:validate. |
| resolve | MinimalTracingChannel<GraphQLResolveContext> | Tracing channel for graphql:resolve. |
| subscribe | MinimalTracingChannel<GraphQLSubscribeContext> | Tracing channel for graphql:subscribe. |
Category: Request Pipeline
Functions:
graphql()graphqlSync()
Types:
GraphQLArgs
Functions
graphql()
Parses, validates, and executes a GraphQL document against a schema.
This is the primary entry point for fulfilling GraphQL operations. Use this when you want a single-call request lifecycle that returns a promise in all cases.
More sophisticated GraphQL servers, such as those which persist queries, may wish to separate the validation and execution phases to a static-time tooling step and a server runtime step.
Signature:
graphql(
args: GraphQLArgs,
): Promise<ExecutionResult>;
| Name | Type | Description |
|---|---|---|
| args | GraphQLArgs | Request execution arguments, including schema and source. |
| Type | Description |
|---|---|
Promise<ExecutionResult> | A promise that resolves to an execution result or validation errors. |
// Execute a complete asynchronous request with variables.
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(
`
type Query {
greeting(name: String!): String
}
`,
{
supplementalConfig: {
objectTypes: {
Query: {
fields: {
greeting: (_source, { name }) => `Hello, ${name}!`,
},
},
},
},
},
);
const result = await graphql({
schema,
source: 'query SayHello($name: String!) { greeting(name: $name) }',
variableValues: { name: 'Ada' },
operationName: 'SayHello',
});
result; // => { data: { greeting: 'Hello, Ada!' } }// This variant supplies context plus custom field and type resolvers.
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
interface Named {
name: String!
}
type User implements Named {
name: String!
}
type Query {
viewer: Named
}
`);
const result = await graphql({
schema,
source: '{ viewer { __typename name } }',
rootValue: { viewer: { kind: 'user', name: 'Ada' } },
contextValue: { locale: 'en' },
fieldResolver: (source, _args, context, info) => {
context.locale; // => 'en'
return source[info.fieldName];
},
typeResolver: (value) => {
return value.kind === 'user' ? 'User' : undefined;
},
});
result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } }// This variant customizes the request pipeline with a harness.
import { buildSchema, defaultHarness, graphql } from 'graphql';
const schema = buildSchema(
`
type Query {
greeting: String
}
`,
{
supplementalConfig: {
objectTypes: {
Query: {
fields: {
greeting: () => 'Hello',
},
},
},
},
},
);
const stages = [];
const abortController = new AbortController();
const harness = {
parse: (...args) => {
stages.push('parse');
return defaultHarness.parse(...args);
},
validate: (...args) => {
stages.push('validate');
return defaultHarness.validate(...args);
},
execute: (...args) => {
stages.push('execute');
return defaultHarness.execute(...args);
},
subscribe: (...args) => {
stages.push('subscribe');
return defaultHarness.subscribe(...args);
},
};
const result = await graphql({
schema,
source: '{ greeting }',
rules: [],
maxErrors: 25,
hideSuggestions: true,
noLocation: true,
abortSignal: abortController.signal,
harness,
});
result; // => { data: { greeting: 'Hello' } }
stages; // => ['parse', 'validate', 'execute']graphqlSync()
Parses, validates, and executes a GraphQL document synchronously.
This function guarantees that execution completes synchronously, or throws an error, assuming that all field resolvers are also synchronous. It throws when any resolver returns a promise.
Signature:
graphqlSync(
args: GraphQLArgs,
): ExecutionResult;
| Name | Type | Description |
|---|---|---|
| args | GraphQLArgs | Request execution arguments, including schema and source. |
| Type | Description |
|---|---|
ExecutionResult | Completed execution output, or request errors if parsing or validation fails. |
// Execute a complete synchronous request with variables.
import { graphqlSync, buildSchema } from 'graphql';
const schema = buildSchema(
`
type Query {
greeting(name: String!): String
}
`,
{
supplementalConfig: {
objectTypes: {
Query: {
fields: {
greeting: (_source, { name }) => `Hello, ${name}!`,
},
},
},
},
},
);
const result = graphqlSync({
schema,
source: 'query SayHello($name: String!) { greeting(name: $name) }',
variableValues: { name: 'Ada' },
operationName: 'SayHello',
});
result; // => { data: { greeting: 'Hello, Ada!' } }// This variant uses a synchronous custom field resolver and context.
import { graphqlSync, buildSchema } from 'graphql';
const schema = buildSchema(`
type Query {
greeting: String
}
`);
const result = graphqlSync({
schema,
source: '{ greeting }',
fieldResolver: (_source, _args, contextValue) => {
return contextValue.defaultGreeting;
},
contextValue: { defaultGreeting: 'Hello' },
});
result; // => { data: { greeting: 'Hello' } }Types
GraphQLArgs
Interface. Describes the input object accepted by graphql and graphqlSync.
These arguments describe the full parse, validate, and execute lifecycle for a GraphQL request. They include parser options, validation options, execution options, and an optional harness for replacing pipeline stages.
graphql and graphqlSync do not support incremental delivery (@defer and
@stream); use experimentalExecuteIncrementally after parsing and
validating when incremental delivery is required.
interface GraphQLArgs
extends ParseOptions,
ValidationOptions
| Name | Type | Description |
|---|---|---|
| harness? | GraphQLHarness | Custom parse, validate, execute, and subscribe functions for this request pipeline. |
| source | string | Source | A GraphQL language-formatted string or source object representing the requested operation. |
| rules? | readonly ValidationRule[] | Validation rules to use instead of the specified rules. |
Category: Harness
Constants:
defaultHarness
Types:
GraphQLParseFnGraphQLValidateFnGraphQLExecuteFnGraphQLSubscribeFnGraphQLHarness
Constants
defaultHarness
Default harness backed by GraphQL.js parse, validate, execute, and subscribe implementations.
GraphQLHarness
Types
GraphQLParseFn
Type alias. Function used by a GraphQL harness to parse GraphQL source text.
type GraphQLParseFn = (
args: Parameters<typeof parse>,
) => PromiseOrValue<ReturnType<typeof parse>>;
GraphQLValidateFn
Type alias. Function used by a GraphQL harness to validate a parsed document.
type GraphQLValidateFn = (
args: Parameters<typeof validate>,
) => PromiseOrValue<ReturnType<typeof validate>>;
GraphQLExecuteFn
Type alias. Function used by a GraphQL harness to execute a valid operation.
type GraphQLExecuteFn = (
args: Parameters<typeof execute>,
) => ReturnType<typeof execute>;
GraphQLSubscribeFn
Type alias. Function used by a GraphQL harness to create a subscription response stream.
type GraphQLSubscribeFn = (
args: Parameters<typeof subscribe>,
) => ReturnType<typeof subscribe>;
GraphQLHarness
Interface. Overrides for the parse, validate, execute, and subscribe stages used by the
high-level graphql and graphqlSync request pipeline.
| Name | Type | Description |
|---|---|---|
| parse | GraphQLParseFn | Parses GraphQL source text into a document AST. |
| validate | GraphQLValidateFn | Validates a document AST against a schema. |
| execute | GraphQLExecuteFn | Executes a valid operation. |
| subscribe | GraphQLSubscribeFn | Creates a response stream for a subscription operation. |
Category: Version
Constants:
versionversionInfo
Constants
version
A string containing the version of the GraphQL.js library
string
versionInfo
An object containing the components of the GraphQL.js version string
Readonly<{
major: number;
minor: number;
patch: number;
preReleaseTag: string | null;
}>