website/pages/api-v17/graphql.mdx
import { ApiSignature, ApiType } from '../../components/ApiCode';
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:
<a href="/api-v17/graphql#enabledevmode">enableDevMode()</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#isdevmodeenabled">isDevModeEnabled()</a>
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:
<ApiSignature parts={[["name", "enableDevMode"], "(): ", ["keyword", "void"], ";"]} />
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Example</div>import { enableDevMode, isDevModeEnabled } from 'graphql/devMode';
isDevModeEnabled(); // => false
enableDevMode();
isDevModeEnabled(); // => true
Returns whether GraphQL.js development mode has been enabled for this module instance.
Signature:
<ApiSignature parts={[["name", "isDevModeEnabled"], "(): ", ["keyword", "boolean"], ";"]} />
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Returns</div> <table> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><ApiType parts={[["keyword", "boolean"]]} /></td> <td>True when development mode is enabled.</td> </tr> </tbody> </table> <hr className="api-subsection-divider" /> <div className="api-subsection-title">Example</div>import { enableDevMode, isDevModeEnabled } from 'graphql/devMode';
enableDevMode();
isDevModeEnabled(); // => true
<a href="/api-v17/graphql#graphqlparsecontext">GraphQLParseContext</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlvalidatecontext">GraphQLValidateContext</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlexecutecontext">GraphQLExecuteContext</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlexecuterootselectionsetcontext">GraphQLExecuteRootSelectionSetContext</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlexecutevariablecoercioncontext">GraphQLExecuteVariableCoercionContext</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlsubscribecontext">GraphQLSubscribeContext</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlresolvecontext">GraphQLResolveContext</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlchannelcontextbyname">GraphQLChannelContextByName</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlchannels">GraphQLChannels</a>
Interface. Context published on the sync-only graphql:parse channel.
Interface. Context published on the sync-only graphql:validate channel.
Interface. Context published on graphql:execute.
Returned results may contain GraphQL errors collected during execution.
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Members</div> <table> <thead> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>schema</td> <td><ApiType parts={[["link", "GraphQLSchema", "/api-v17/type#graphqlschema"]]} /></td> <td>Schema used for execution.</td> </tr> <tr> <td>document</td> <td><ApiType parts={[["link", "DocumentNode", "/api-v17/language#documentnode"]]} /></td> <td>Parsed document being executed.</td> </tr> <tr> <td>rawVariableValues</td> <td><ApiType parts={[["type", "Maybe"], "\u003c\u007b\n ", ["keyword", "readonly"], " [", ["parameter", "variable"], ": ", ["keyword", "string"], "]: ", ["keyword", "unknown"], ";\n\u007d\u003e"]} /></td> <td>Raw variable values provided by the caller before coercion.</td> </tr> <tr> <td>operationName</td> <td><ApiType parts={[["keyword", "string"], " \u007c ", ["keyword", "undefined"]]} /></td> <td>Selected operation name, if one is available.</td> </tr> <tr> <td>operationType</td> <td><ApiType parts={[["link", "OperationTypeNode", "/api-v17/language#operationtypenode"], " \u007c ", ["keyword", "undefined"]]} /></td> <td>Selected operation type, if one is available.</td> </tr> <tr> <td>error?</td> <td><ApiType parts={[["keyword", "unknown"]]} /></td> <td>Error thrown or rejected while executing, when execution fails abruptly.</td> </tr> <tr> <td>result?</td> <td><ApiType parts={[["link", "ExecutionResult", "/api-v17/execution#executionresult"], " \u007c ", ["link", "ExperimentalIncrementalExecutionResults", "/api-v17/execution#experimentalincrementalexecutionresults"]]} /></td> <td>Execution result returned by execution, including GraphQL errors.</td> </tr> </tbody> </table> <hr className="api-item-divider" />Interface. Context published on graphql:execute:rootSelectionSet.
Returned results may contain GraphQL errors collected during execution.
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Members</div> <table> <thead> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>schema</td> <td><ApiType parts={[["link", "GraphQLSchema", "/api-v17/type#graphqlschema"]]} /></td> <td>Schema used for execution.</td> </tr> <tr> <td>document</td> <td><ApiType parts={[["link", "DocumentNode", "/api-v17/language#documentnode"]]} /></td> <td>Parsed document being executed.</td> </tr> <tr> <td>operation</td> <td><ApiType parts={[["link", "OperationDefinitionNode", "/api-v17/language#operationdefinitionnode"]]} /></td> <td>Operation definition selected for execution.</td> </tr> <tr> <td>rawVariableValues</td> <td><ApiType parts={[["type", "Maybe"], "\u003c\u007b\n ", ["keyword", "readonly"], " [", ["parameter", "variable"], ": ", ["keyword", "string"], "]: ", ["keyword", "unknown"], ";\n\u007d\u003e"]} /></td> <td>Raw variable values provided by the caller before coercion.</td> </tr> <tr> <td>operationName</td> <td><ApiType parts={[["keyword", "string"], " \u007c ", ["keyword", "undefined"]]} /></td> <td>Selected operation name, if one is available.</td> </tr> <tr> <td>operationType</td> <td><ApiType parts={[["link", "OperationTypeNode", "/api-v17/language#operationtypenode"]]} /></td> <td>Selected operation type.</td> </tr> <tr> <td>error?</td> <td><ApiType parts={[["keyword", "unknown"]]} /></td> <td>Error thrown or rejected while executing the root selection set.</td> </tr> <tr> <td>result?</td> <td><ApiType parts={[["link", "ExecutionResult", "/api-v17/execution#executionresult"], " \u007c ", ["link", "ExperimentalIncrementalExecutionResults", "/api-v17/execution#experimentalincrementalexecutionresults"]]} /></td> <td>Execution result returned from the root selection set, including GraphQLerrors.</td> </tr>
</tbody> </table> <hr className="api-item-divider" />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.
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.
errors.</td> </tr>
</tbody> </table> <hr className="api-item-divider" />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.
Interface. Mapping from tracing channel name to the context type published on it.
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Members</div> <table> <thead> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>graphql:parse</td> <td><ApiType parts={[["link", "GraphQLParseContext", "/api-v17/graphql#graphqlparsecontext"]]} /></td> <td>Context published on <code>{"graphql:parse"}</code>.</td> </tr> <tr> <td>graphql:validate</td> <td><ApiType parts={[["link", "GraphQLValidateContext", "/api-v17/graphql#graphqlvalidatecontext"]]} /></td> <td>Context published on <code>{"graphql:validate"}</code>.</td> </tr> <tr> <td>graphql:execute</td> <td><ApiType parts={[["link", "GraphQLExecuteContext", "/api-v17/graphql#graphqlexecutecontext"]]} /></td> <td>Context published on <code>{"graphql:execute"}</code>.</td> </tr> <tr> <td>graphql:execute:variableCoercion</td> <td><ApiType parts={[["link", "GraphQLExecuteVariableCoercionContext", "/api-v17/graphql#graphqlexecutevariablecoercioncontext"]]} /></td> <td>Context published on <code>{"graphql:execute:variableCoercion"}</code>.</td> </tr> <tr> <td>graphql:execute:rootSelectionSet</td> <td><ApiType parts={[["link", "GraphQLExecuteRootSelectionSetContext", "/api-v17/graphql#graphqlexecuterootselectionsetcontext"]]} /></td> <td>Context published on <code>{"graphql:execute:rootSelectionSet"}</code>.</td> </tr> <tr> <td>graphql:subscribe</td> <td><ApiType parts={[["link", "GraphQLSubscribeContext", "/api-v17/graphql#graphqlsubscribecontext"]]} /></td> <td>Context published on <code>{"graphql:subscribe"}</code>.</td> </tr> <tr> <td>graphql:resolve</td> <td><ApiType parts={[["link", "GraphQLResolveContext", "/api-v17/graphql#graphqlresolvecontext"]]} /></td> <td>Context published on <code>{"graphql:resolve"}</code>.</td> </tr> </tbody> </table> <hr className="api-item-divider" />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.
<a href="/api-v17/graphql#graphql">graphql()</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlsync">graphqlSync()</a>
<a href="/api-v17/graphql#graphqlargs">GraphQLArgs</a>
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:
<ApiSignature parts={[["name", "graphql"], "(\n ", ["parameter", "args"], ": ", ["link", "GraphQLArgs", "/api-v17/graphql#graphqlargs"], ",\n): ", ["type", "Promise"], "\u003c", ["link", "ExecutionResult", "/api-v17/execution#executionresult"], "\u003e;"]} />
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Arguments</div> <table> <thead> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>args</td> <td><ApiType parts={[["link", "GraphQLArgs", "/api-v17/graphql#graphqlargs"]]} /></td> <td>Request execution arguments, including schema and source.</td> </tr> </tbody> </table> <hr className="api-subsection-divider" /> <div className="api-subsection-title">Returns</div> <table> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><ApiType parts={[["type", "Promise"], "\u003c", ["link", "ExecutionResult", "/api-v17/execution#executionresult"], "\u003e"]} /></td> <td>A promise that resolves to an execution result or validation errors.</td> </tr> </tbody> </table> <hr className="api-subsection-divider" /> <div className="api-subsection-title">Example 1</div>// Execute a complete asynchronous request with variables.
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Query {
greeting(name: String!): String
}
`);
const result = await graphql({
schema,
source: 'query SayHello($name: String!) { greeting(name: $name) }',
rootValue: {
greeting: ({ name }) => `Hello, ${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
}
`);
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 }',
rootValue: { greeting: 'Hello' },
rules: [],
maxErrors: 25,
hideSuggestions: true,
noLocation: true,
abortSignal: abortController.signal,
harness,
});
result; // => { data: { greeting: 'Hello' } }
stages; // => ['parse', 'validate', 'execute']
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:
<ApiSignature parts={[["name", "graphqlSync"], "(\n ", ["parameter", "args"], ": ", ["link", "GraphQLArgs", "/api-v17/graphql#graphqlargs"], ",\n): ", ["link", "ExecutionResult", "/api-v17/execution#executionresult"], ";"]} />
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Arguments</div> <table> <thead> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>args</td> <td><ApiType parts={[["link", "GraphQLArgs", "/api-v17/graphql#graphqlargs"]]} /></td> <td>Request execution arguments, including schema and source.</td> </tr> </tbody> </table> <hr className="api-subsection-divider" /> <div className="api-subsection-title">Returns</div> <table> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><ApiType parts={[["link", "ExecutionResult", "/api-v17/execution#executionresult"]]} /></td> <td>Completed execution output, or request errors if parsing orvalidation fails.</td> </tr>
</tbody> </table> <hr className="api-subsection-divider" /> <div className="api-subsection-title">Example 1</div>// Execute a complete synchronous request with variables.
import { graphqlSync, buildSchema } from 'graphql';
const schema = buildSchema(`
type Query {
greeting(name: String!): String
}
`);
const result = graphqlSync({
schema,
source: 'query SayHello($name: String!) { greeting(name: $name) }',
rootValue: {
greeting: ({ name }) => `Hello, ${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' } }
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.
<ApiSignature parts={[["keyword", "interface"], " ", ["name", "GraphQLArgs"], "\n ", ["keyword", "extends"], " ", ["link", "ParseOptions", "/api-v17/language#parseoptions"], ", ", ["link", "ValidationOptions", "/api-v17/validation#validationoptions"]]} />
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Members</div> <table> <thead> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>harness?</td> <td><ApiType parts={[["link", "GraphQLHarness", "/api-v17/graphql#graphqlharness"]]} /></td> <td>Custom parse, validate, execute, and subscribe functions for this requestpipeline.</td> </tr> <tr> <td>source</td> <td><ApiType parts={[["keyword", "string"], " \u007c ", ["link", "Source", "/api-v17/language#source"]]} /></td> <td>A GraphQL language-formatted string or source object representing the
requested operation.</td> </tr> <tr> <td>rules?</td> <td><ApiType parts={[["keyword", "readonly"], " ", ["link", "ValidationRule", "/api-v17/validation#validationrule"], "[]"]} /></td> <td>Validation rules to use instead of the specified rules.</td> </tr>
</tbody> </table><a href="/api-v17/graphql#defaultharness">defaultHarness</a>
<a href="/api-v17/graphql#graphqlparsefn">GraphQLParseFn</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlvalidatefn">GraphQLValidateFn</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlexecutefn">GraphQLExecuteFn</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlsubscribefn">GraphQLSubscribeFn</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#graphqlharness">GraphQLHarness</a>
Default harness backed by GraphQL.js parse, validate, execute, and subscribe implementations.
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Type</div><ApiType parts={[["link", "GraphQLHarness", "/api-v17/graphql#graphqlharness"]]} />
Type alias. Function used by a GraphQL harness to parse GraphQL source text.
<ApiSignature parts={[["keyword", "type"], " ", ["name", "GraphQLParseFn"], " = (\n ", ["parameter", "args"], ": ", ["type", "Parameters"], "\u003c", ["keyword", "typeof"], " ", ["link", "parse", "/api-v17/language#parse"], "\u003e,\n) =\u003e ", ["type", "PromiseOrValue"], "\u003c", ["type", "ReturnType"], "\u003c", ["keyword", "typeof"], " ", ["link", "parse", "/api-v17/language#parse"], "\u003e\u003e;"]} />
<hr className="api-item-divider" />Type alias. Function used by a GraphQL harness to validate a parsed document.
<ApiSignature parts={[["keyword", "type"], " ", ["name", "GraphQLValidateFn"], " = (\n ", ["parameter", "args"], ": ", ["type", "Parameters"], "\u003c", ["keyword", "typeof"], " ", ["link", "validate", "/api-v17/validation#validate"], "\u003e,\n) =\u003e ", ["type", "PromiseOrValue"], "\u003c", ["type", "ReturnType"], "\u003c", ["keyword", "typeof"], " ", ["link", "validate", "/api-v17/validation#validate"], "\u003e\u003e;"]} />
<hr className="api-item-divider" />Type alias. Function used by a GraphQL harness to execute a valid operation.
<ApiSignature parts={[["keyword", "type"], " ", ["name", "GraphQLExecuteFn"], " = (\n ", ["parameter", "args"], ": ", ["type", "Parameters"], "\u003c", ["keyword", "typeof"], " ", ["link", "execute", "/api-v17/execution#execute"], "\u003e,\n) =\u003e ", ["type", "ReturnType"], "\u003c", ["keyword", "typeof"], " ", ["link", "execute", "/api-v17/execution#execute"], "\u003e;"]} />
<hr className="api-item-divider" />Type alias. Function used by a GraphQL harness to create a subscription response stream.
<ApiSignature parts={[["keyword", "type"], " ", ["name", "GraphQLSubscribeFn"], " = (\n ", ["parameter", "args"], ": ", ["type", "Parameters"], "\u003c", ["keyword", "typeof"], " ", ["link", "subscribe", "/api-v17/execution#subscribe"], "\u003e,\n) =\u003e ", ["type", "ReturnType"], "\u003c", ["keyword", "typeof"], " ", ["link", "subscribe", "/api-v17/execution#subscribe"], "\u003e;"]} />
<hr className="api-item-divider" />Interface. Overrides for the parse, validate, execute, and subscribe stages used by the
high-level graphql and graphqlSync request pipeline.
<a href="/api-v17/graphql#version">version</a>
<span aria-hidden="true">·</span>
<a href="/api-v17/graphql#versioninfo">versionInfo</a>
A string containing the version of the GraphQL.js library
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Type</div><ApiType parts={[["keyword", "string"]]} />
<hr className="api-item-divider" />An object containing the components of the GraphQL.js version string
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Type</div><ApiType parts={[["type", "Readonly"], "\u003c\u007b\n ", ["property", "major"], ": ", ["keyword", "number"], ";\n ", ["property", "minor"], ": ", ["keyword", "number"], ";\n ", ["property", "patch"], ": ", ["keyword", "number"], ";\n ", ["property", "preReleaseTag"], ": ", ["keyword", "string"], " \u007c ", ["keyword", "null"], ";\n\u007d\u003e"]} />