Back to Graphql Js

Graphql

website/pages/api-v17/graphql.mdx

17.0.236.9 KB
Original Source

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:

ts
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

<div className="api-category-toc"> <p> <strong>Functions:</strong>
<a href="/api-v17/graphql#enabledevmode">enableDevMode()</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#isdevmodeenabled">isDevModeEnabled()</a>
</p> </div>

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:

<ApiSignature parts={[["name", "enableDevMode"], "(): ", ["keyword", "void"], ";"]} />

<hr className="api-subsection-divider" /> <div className="api-subsection-title">Example</div>
ts
import { enableDevMode, isDevModeEnabled } from 'graphql/devMode';

isDevModeEnabled(); // => false
enableDevMode();
isDevModeEnabled(); // => true
<hr className="api-item-divider" />

isDevModeEnabled()

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>
ts
import { enableDevMode, isDevModeEnabled } from 'graphql/devMode';

enableDevMode();

isDevModeEnabled(); // => true

Category: Diagnostics

<div className="api-category-toc"> <p> <strong>Types:</strong>
<a href="/api-v17/graphql#graphqlparsecontext">GraphQLParseContext</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlvalidatecontext">GraphQLValidateContext</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlexecutecontext">GraphQLExecuteContext</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlexecuterootselectionsetcontext">GraphQLExecuteRootSelectionSetContext</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlexecutevariablecoercioncontext">GraphQLExecuteVariableCoercionContext</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlsubscribecontext">GraphQLSubscribeContext</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlresolvecontext">GraphQLResolveContext</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlchannelcontextbyname">GraphQLChannelContextByName</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlchannels">GraphQLChannels</a>
</p> </div>

Types

GraphQLParseContext

Interface. Context published on the sync-only graphql:parse channel.

<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>source</td> <td><ApiType parts={[["keyword", "string"], " \u007c ", ["link", "Source", "/api-v17/language#source"]]} /></td> <td>Source text or source object passed to the parser.</td> </tr> <tr> <td>error?</td> <td><ApiType parts={[["keyword", "unknown"]]} /></td> <td>Error thrown while parsing, when parsing fails.</td> </tr> <tr> <td>result?</td> <td><ApiType parts={[["link", "DocumentNode", "/api-v17/language#documentnode"]]} /></td> <td>Parsed document, when parsing succeeds.</td> </tr> </tbody> </table> <hr className="api-item-divider" />

GraphQLValidateContext

Interface. Context published on the sync-only graphql:validate channel.

<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 validation.</td> </tr> <tr> <td>document</td> <td><ApiType parts={[["link", "DocumentNode", "/api-v17/language#documentnode"]]} /></td> <td>Parsed document being validated.</td> </tr> <tr> <td>error?</td> <td><ApiType parts={[["keyword", "unknown"]]} /></td> <td>Error thrown while validating, when validation fails abruptly.</td> </tr> <tr> <td>result?</td> <td><ApiType parts={[["keyword", "readonly"], " ", ["link", "GraphQLError", "/api-v17/error#graphqlerror"], "[]"]} /></td> <td>Validation errors returned by validation.</td> </tr> </tbody> </table> <hr className="api-item-divider" />

GraphQLExecuteContext

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" />

GraphQLExecuteRootSelectionSetContext

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 GraphQL

errors.</td> </tr>

</tbody> </table> <hr className="api-item-divider" />

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.

<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 variable coercion.</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 whose variables are being coerced.</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 while coercing variables, when coercion fails abruptly.</td> </tr> <tr> <td>result?</td> <td><ApiType parts={["\u007c \u007b ", ["property", "variableValues"], ": ", ["link", "VariableValues", "/api-v17/execution#variablevalues"], " \u007d\n\u007c \u007b ", ["property", "errors"], ": ", ["keyword", "readonly"], " ", ["link", "GraphQLError", "/api-v17/error#graphqlerror"], "[] \u007d"]} /></td> <td>Coerced variable values or coercion errors returned by coercion.</td> </tr> </tbody> </table> <hr className="api-item-divider" />

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.

<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 subscription execution.</td> </tr> <tr> <td>document</td> <td><ApiType parts={[["link", "DocumentNode", "/api-v17/language#documentnode"]]} /></td> <td>Parsed subscription document.</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 subscribing, when setup fails abruptly.</td> </tr> <tr> <td>result?</td> <td><ApiType parts={["\u007c ", ["link", "ExecutionResult", "/api-v17/execution#executionresult"], "\n\u007c ", ["type", "AsyncGenerator"], "\u003c", ["link", "ExecutionResult", "/api-v17/execution#executionresult"], ", ", ["keyword", "void"], ", ", ["keyword", "void"], "\u003e"]} /></td> <td>Subscription response stream, or an ExecutionResult containing GraphQL

errors.</td> </tr>

</tbody> </table> <hr className="api-item-divider" />

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.

<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>fieldName</td> <td><ApiType parts={[["keyword", "string"]]} /></td> <td>Field name being resolved.</td> </tr> <tr> <td>alias</td> <td><ApiType parts={[["keyword", "string"]]} /></td> <td>Response alias for the field being resolved.</td> </tr> <tr> <td>parentType</td> <td><ApiType parts={[["keyword", "string"]]} /></td> <td>Parent type name for the field being resolved.</td> </tr> <tr> <td>fieldType</td> <td><ApiType parts={[["keyword", "string"]]} /></td> <td>Return type string for the field being resolved.</td> </tr> <tr> <td>args</td> <td><ApiType parts={[["type", "ObjMap"], "\u003c", ["keyword", "unknown"], "\u003e"]} /></td> <td>Argument values passed to the resolver.</td> </tr> <tr> <td>isDefaultResolver</td> <td><ApiType parts={[["keyword", "boolean"]]} /></td> <td>Whether the field is using the default resolver.</td> </tr> <tr> <td>fieldPath</td> <td><ApiType parts={[["keyword", "string"]]} /></td> <td>Response path for the field being resolved.</td> </tr> <tr> <td>error?</td> <td><ApiType parts={[["keyword", "unknown"]]} /></td> <td>Error thrown or rejected by the resolver, when resolution fails.</td> </tr> <tr> <td>result?</td> <td><ApiType parts={[["keyword", "unknown"]]} /></td> <td>Value returned by the resolver, when resolution succeeds.</td> </tr> </tbody> </table> <hr className="api-item-divider" />

GraphQLChannelContextByName

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" />

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.

<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>execute</td> <td><ApiType parts={[["type", "MinimalTracingChannel"], "\u003c", ["link", "GraphQLExecuteContext", "/api-v17/graphql#graphqlexecutecontext"], "\u003e"]} /></td> <td>Tracing channel for <code>{"graphql:execute"}</code>.</td> </tr> <tr> <td>executeVariableCoercion</td> <td><ApiType parts={[["type", "MinimalTracingChannel"], "\u003c", ["link", "GraphQLExecuteVariableCoercionContext", "/api-v17/graphql#graphqlexecutevariablecoercioncontext"], "\u003e"]} /></td> <td>Tracing channel for <code>{"graphql:execute:variableCoercion"}</code>.</td> </tr> <tr> <td>executeRootSelectionSet</td> <td><ApiType parts={[["type", "MinimalTracingChannel"], "\u003c", ["link", "GraphQLExecuteRootSelectionSetContext", "/api-v17/graphql#graphqlexecuterootselectionsetcontext"], "\u003e"]} /></td> <td>Tracing channel for <code>{"graphql:execute:rootSelectionSet"}</code>.</td> </tr> <tr> <td>parse</td> <td><ApiType parts={[["type", "MinimalTracingChannel"], "\u003c", ["link", "GraphQLParseContext", "/api-v17/graphql#graphqlparsecontext"], "\u003e"]} /></td> <td>Tracing channel for <code>{"graphql:parse"}</code>.</td> </tr> <tr> <td>validate</td> <td><ApiType parts={[["type", "MinimalTracingChannel"], "\u003c", ["link", "GraphQLValidateContext", "/api-v17/graphql#graphqlvalidatecontext"], "\u003e"]} /></td> <td>Tracing channel for <code>{"graphql:validate"}</code>.</td> </tr> <tr> <td>resolve</td> <td><ApiType parts={[["type", "MinimalTracingChannel"], "\u003c", ["link", "GraphQLResolveContext", "/api-v17/graphql#graphqlresolvecontext"], "\u003e"]} /></td> <td>Tracing channel for <code>{"graphql:resolve"}</code>.</td> </tr> <tr> <td>subscribe</td> <td><ApiType parts={[["type", "MinimalTracingChannel"], "\u003c", ["link", "GraphQLSubscribeContext", "/api-v17/graphql#graphqlsubscribecontext"], "\u003e"]} /></td> <td>Tracing channel for <code>{"graphql:subscribe"}</code>.</td> </tr> </tbody> </table>

Category: Request Pipeline

<div className="api-category-toc"> <p> <strong>Functions:</strong>
<a href="/api-v17/graphql#graphql">graphql()</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlsync">graphqlSync()</a>
</p> <p> <strong>Types:</strong>
<a href="/api-v17/graphql#graphqlargs">GraphQLArgs</a>
</p> </div>

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:

<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>
ts
// 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!' } }
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Example 2</div>
ts
// 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' } } }
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Example 3</div>
ts
// 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']
<hr className="api-item-divider" />

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:

<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 or

validation fails.</td> </tr>

</tbody> </table> <hr className="api-subsection-divider" /> <div className="api-subsection-title">Example 1</div>
ts
// 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!' } }
<hr className="api-subsection-divider" /> <div className="api-subsection-title">Example 2</div>
ts
// 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.

<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 request

pipeline.</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>

Category: Harness

<div className="api-category-toc"> <p> <strong>Constants:</strong>
<a href="/api-v17/graphql#defaultharness">defaultHarness</a>
</p> <p> <strong>Types:</strong>
<a href="/api-v17/graphql#graphqlparsefn">GraphQLParseFn</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlvalidatefn">GraphQLValidateFn</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlexecutefn">GraphQLExecuteFn</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlsubscribefn">GraphQLSubscribeFn</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#graphqlharness">GraphQLHarness</a>
</p> </div>

Constants

defaultHarness

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"]]} />

Types

GraphQLParseFn

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" />

GraphQLValidateFn

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" />

GraphQLExecuteFn

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" />

GraphQLSubscribeFn

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" />

GraphQLHarness

Interface. Overrides for the parse, validate, execute, and subscribe stages used by the high-level graphql and graphqlSync request pipeline.

<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>parse</td> <td><ApiType parts={[["link", "GraphQLParseFn", "/api-v17/graphql#graphqlparsefn"]]} /></td> <td>Parses GraphQL source text into a document AST.</td> </tr> <tr> <td>validate</td> <td><ApiType parts={[["link", "GraphQLValidateFn", "/api-v17/graphql#graphqlvalidatefn"]]} /></td> <td>Validates a document AST against a schema.</td> </tr> <tr> <td>execute</td> <td><ApiType parts={[["link", "GraphQLExecuteFn", "/api-v17/graphql#graphqlexecutefn"]]} /></td> <td>Executes a valid operation.</td> </tr> <tr> <td>subscribe</td> <td><ApiType parts={[["link", "GraphQLSubscribeFn", "/api-v17/graphql#graphqlsubscribefn"]]} /></td> <td>Creates a response stream for a subscription operation.</td> </tr> </tbody> </table>

Category: Version

<div className="api-category-toc"> <p> <strong>Constants:</strong>
<a href="/api-v17/graphql#version">version</a>
<span aria-hidden="true">&middot;</span>
<a href="/api-v17/graphql#versioninfo">versionInfo</a>
</p> </div>

Constants

version

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" />

versionInfo

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"]} />