graphql

Search for an npm package

graphql

module "graphql" {

@category — Version

more
less

A string containing the version of the GraphQL.js library

export const version: string = ...

An object containing the components of the GraphQL.js version string

export const versionInfo: Readonly<{
major: number;
minor: number;
patch: number;
preReleaseTag: string | null;
}> = ...

Describes the input object accepted by graphql and graphqlSync.

more
less

These arguments describe the full parse, validate, and execute lifecycle for a GraphQL request.

@category — Request Pipeline

export interface GraphQLArgs {

The GraphQL type system to use when validating and executing a query.

schema: GraphQLSchema;

A GraphQL language-formatted string or source object representing the requested operation.

source: string | Source;

The value provided as the first argument to resolver functions on the top level type, such as the query object type.

rootValue?: unknown;

Application context value passed to every resolver.

more
less

Use this for shared request data such as the currently logged in user and connections to databases or other services.

contextValue?: unknown;

A mapping of variable name to runtime value for variables defined by the operation.

variableValues?: Maybe<{
readonly [key: string]: unknown;
}>;

The operation to execute when the source contains multiple possible operations. This can be omitted when the source contains only one operation.

operationName?: Maybe<string>;

A resolver function to use when one is not provided by the schema.

more
less

If not provided, the default field resolver is used, which looks for a value or method on the source value with the field's name.

fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;

A type resolver function to use when none is provided by the schema.

more
less

If not provided, the default type resolver is used, which looks for a __typename field or alternatively calls the isTypeOf method.

typeResolver?: Maybe<GraphQLTypeResolver<any, any>>;
}
Referenced by
Unexported symbols referenced here

Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/

more
less

@internal —

type Maybe<T> = null | undefined | T
Referenced by

Parses, validates, and executes a GraphQL document against a schema.

more
less

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.

@param — - Request execution arguments, including schema and source.

@returns — A promise that resolves to an execution result or validation errors.

@example — ```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!' } }

@example — ```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' } } }

@category — Request Pipeline

export function graphql(args: GraphQLArgs): Promise<ExecutionResult>

Parses, validates, and executes a GraphQL document synchronously.

more
less

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.

@param — - Request execution arguments, including schema and source.

@returns — Completed execution output, or request errors if parsing or validation fails.

@example — ```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!' } }

@example — ```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' } }

@category — Request Pipeline

export function graphqlSync(args: GraphQLArgs): ExecutionResult

Resolves a thunked object map.

more
less

@param — - The thunk or value to resolve.

@returns — The resolved object map.

@typeParam — T - The object-map value type resolved from the thunk or map.

@example — ```ts import { GraphQLString, resolveObjMapThunk } from 'graphql/type';

const lazyFields = resolveObjMapThunk(() => ({ name: GraphQLString })); const fields = resolveObjMapThunk({ name: GraphQLString });

lazyFields.name; // => GraphQLString fields.name; // => GraphQLString

export function resolveObjMapThunk<T>(thunk: ThunkObjMap<T>): ObjMap<T>
Unexported symbols referenced here

Resolves a thunked readonly array.

more
less

@param — - The thunk or value to resolve.

@returns — The resolved readonly array.

@typeParam — T - The element type resolved from the thunk or array.

@example — ```ts import { GraphQLString, resolveReadonlyArrayThunk } from 'graphql/type';

const lazyFields = resolveReadonlyArrayThunk(() => [GraphQLString]); const fields = resolveReadonlyArrayThunk([GraphQLString]);

lazyFields; // => [GraphQLString] fields; // => [GraphQLString]

export function resolveReadonlyArrayThunk<T>(thunk: ThunkReadonlyArray<T>): readonly T[]

Schema Definition

more
less

A Schema is created by supplying the root types of each type of operation, query and mutation (optional). A schema definition is then supplied to the validator and executor.

@example — ```ts const MyAppQueryRootType = new GraphQLObjectType({ name: 'Query', fields: { greeting: { type: GraphQLString }, }, });

const MyAppMutationRootType = new GraphQLObjectType({ name: 'Mutation', fields: { setGreeting: { type: GraphQLString }, }, });

const MyAppSchema = new GraphQLSchema({ query: MyAppQueryRootType, mutation: MyAppMutationRootType, });

@example — When the schema is constructed, by default only the types that are reachable
by traversing the root types are included, other types must be explicitly
referenced.
```ts
const characterInterface = new GraphQLInterfaceType({
name: 'Character',
fields: {
name: { type: GraphQLString },
},
});
const humanType = new GraphQLObjectType({
name: 'Human',
interfaces: [characterInterface],
fields: {
name: { type: GraphQLString },
},
});
const droidType = new GraphQLObjectType({
name: 'Droid',
interfaces: [characterInterface],
fields: {
name: { type: GraphQLString },
},
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
hero: { type: characterInterface },
},
}),
// Since this schema references only the `Character` interface it's
// necessary to explicitly list the types that implement it if
// you want them to be included in the final schema.
types: [humanType, droidType],
});

@example — If an array of directives are provided to GraphQLSchema, that will be the exact list of directives represented and allowed. If directives is not provided then a default set of the specified directives (e.g. @include and @skip) will be used. If you wish to provide additional directives to these specified directives, you must explicitly declare them.

const MyAppSchema = new GraphQLSchema({
query: MyAppQueryRootType,
directives: specifiedDirectives.concat([myCustomDirective]),
});
export class GraphQLSchema {

Creates a GraphQLSchema instance.

more
less

@param — - Configuration describing this object.

@example — ```ts // Create a schema with the required query root. import { GraphQLObjectType, GraphQLSchema, GraphQLString, } from 'graphql/type';

const Query = new GraphQLObjectType({ name: 'Query', fields: { greeting: { type: GraphQLString, resolve: () => 'Hello', }, }, });

const schema = new GraphQLSchema({ description: 'The application schema.', query: Query, });

schema.getQueryType(); // => Query schema.description; // => 'The application schema.'

@example — ```ts
// This variant configures every schema option, including directives and extensions.
import { DirectiveLocation, parse } from 'graphql/language';
import {
GraphQLBoolean,
GraphQLDirective,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
} from 'graphql/type';
const Query = new GraphQLObjectType({
name: 'Query',
fields: { greeting: { type: GraphQLString } },
});
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: { setGreeting: { type: GraphQLString } },
});
const Subscription = new GraphQLObjectType({
name: 'Subscription',
fields: { greetingChanged: { type: GraphQLString } },
});
const AuditEvent = new GraphQLObjectType({
name: 'AuditEvent',
fields: { message: { type: GraphQLString } },
});
const authDirective = new GraphQLDirective({
name: 'auth',
locations: [DirectiveLocation.FIELD_DEFINITION],
args: { required: { type: GraphQLBoolean } },
});
const schemaDocument = parse(`
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
extend schema
@auth — `);
const schema = new GraphQLSchema({
description: 'Operations exposed by the application.',
query: Query,
mutation: Mutation,
subscription: Subscription,
types: [AuditEvent],
directives: [authDirective],
extensions: { owner: 'platform' },
astNode: schemaDocument.definitions[0],
extensionASTNodes: [ schemaDocument.definitions[1] ],
assumeValid: true,
});
schema.getMutationType(); // => Mutation
schema.getSubscriptionType(); // => Subscription
schema.getType('AuditEvent'); // => AuditEvent
schema.getDirective('auth'); // => authDirective
schema.extensions; // => { owner: 'platform' }
constructor(config: Readonly<GraphQLSchemaConfig>)

Human-readable description for this schema element, if provided.

description: Maybe<string>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLSchemaExtensions>;

AST node from which this schema element was built, if available.

astNode: Maybe<SchemaDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes: readonly SchemaExtensionNode[];

Cached schema validation errors, if validation has already run.

more
less

@internal —

__validationErrors: Maybe<readonly GraphQLError[]>;
get [Symbol.toStringTag](): string;

Returns the root object type for query operations.

more
less

@returns — The query root type, if this schema defines one.

@example — ```ts import { buildSchema } from 'graphql/utilities';

const schema = buildSchema( type Query { greeting: String });

schema.getQueryType()?.name; // => 'Query'

getQueryType(): Maybe<GraphQLObjectType>;

Returns the root object type for mutation operations.

more
less

@returns — The mutation root type, if this schema defines one.

@example — ```ts import { buildSchema } from 'graphql/utilities';

const schema = buildSchema(` type Query { greeting: String }

type Mutation { setGreeting(value: String!): String } `);

schema.getMutationType()?.name; // => 'Mutation'

getMutationType(): Maybe<GraphQLObjectType>;

Returns the root object type for subscription operations.

more
less

@returns — The subscription root type, if this schema defines one.

@example — ```ts import { buildSchema } from 'graphql/utilities';

const schema = buildSchema(` type Query { greeting: String }

type Subscription { greetings: String } `);

schema.getSubscriptionType()?.name; // => 'Subscription'

getSubscriptionType(): Maybe<GraphQLObjectType>;

Returns the root object type for the requested operation kind.

more
less

@param — - Operation kind to resolve.

@returns — The root object type for the operation kind, if this schema defines one.

@example — ```ts import { OperationTypeNode } from 'graphql/language'; import { buildSchema } from 'graphql/utilities';

const schema = buildSchema(` type Query { greeting: String }

type Mutation { setGreeting(value: String!): String } `);

schema.getRootType(OperationTypeNode.QUERY)?.name; // => 'Query' schema.getRootType(OperationTypeNode.MUTATION)?.name; // => 'Mutation' schema.getRootType(OperationTypeNode.SUBSCRIPTION); // => undefined

getRootType(operation: OperationTypeNode): Maybe<GraphQLObjectType>;

Returns all named types known to this schema.

more
less

@returns — A map of schema types keyed by type name.

@example — ```ts import { buildSchema } from 'graphql/utilities';

const schema = buildSchema(` type User { name: String }

type Query { viewer: User } `);

const typeMap = schema.getTypeMap();

typeMap.User.name; // => 'User' typeMap.Query.name; // => 'Query' typeMap.String.name; // => 'String'

getTypeMap(): TypeMap;

Returns the named type with the provided name.

more
less

@param — - The GraphQL name to look up.

@returns — The named schema type, if one exists.

@example — ```ts import { buildSchema } from 'graphql/utilities';

const schema = buildSchema(` type User { name: String }

type Query { viewer: User } `);

schema.getType('User')?.toString(); // => 'User' schema.getType('Missing'); // => undefined

getType(name: string): GraphQLNamedType | undefined;

Returns object types that may be returned for an abstract type.

more
less

@param — - Interface or union type to inspect.

@returns — Object types that may satisfy the abstract type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInterfaceType, assertUnionType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

type Organization implements Node { id: ID! }

union SearchResult = User | Organization

type Query { node: Node search: [SearchResult] } `);

const Node = assertInterfaceType(schema.getType('Node')); const SearchResult = assertUnionType(schema.getType('SearchResult'));

schema.getPossibleTypes(Node).map((type) => type.name); // => ['User', 'Organization'] schema.getPossibleTypes(SearchResult).map((type) => type.name); // => ['User', 'Organization']

getPossibleTypes(abstractType: GraphQLAbstractType): readonly GraphQLObjectType[];

Returns objects and interfaces that implement an interface type.

more
less

@param — - Interface type to inspect.

@returns — Object and interface implementations of the interface.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInterfaceType } from 'graphql/type';

const schema = buildSchema(` interface Resource { url: String! }

interface Image implements Resource { url: String! width: Int }

type Photo implements Resource & Image { url: String! width: Int }

type Query { resource: Resource } `);

const Resource = assertInterfaceType(schema.getType('Resource')); const implementations = schema.getImplementations(Resource);

implementations.interfaces.map((type) => type.name); // => ['Image'] implementations.objects.map((type) => type.name); // => ['Photo']

getImplementations(interfaceType: GraphQLInterfaceType): {
objects: readonly GraphQLObjectType[];
interfaces: readonly GraphQLInterfaceType[];
};

Returns whether one type is a possible runtime subtype of an abstract type.

more
less

@param — - Interface or union type to inspect.

@param — - Object or interface type to test as a possible subtype.

@returns — True when the subtype may satisfy the abstract type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInterfaceType, assertObjectType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

type Review { body: String }

type Query { node: Node review: Review } `);

const Node = assertInterfaceType(schema.getType('Node')); const User = assertObjectType(schema.getType('User')); const Review = assertObjectType(schema.getType('Review'));

schema.isSubType(Node, User); // => true schema.isSubType(Node, Review); // => false

isSubType(abstractType: GraphQLAbstractType, maybeSubType: GraphQLObjectType | GraphQLInterfaceType): boolean;

Returns directives available in this schema.

more
less

@returns — Directives available in this schema.

@example — ```ts import { buildSchema } from 'graphql/utilities';

const schema = buildSchema(` directive

@upper — on FIELD_DEFINITION

type Query { greeting: String

@upper — } `);

schema.getDirectives().map((directive) => directive.name); // => ['include', 'skip', 'deprecated', 'specifiedBy', 'oneOf', 'upper']

getDirectives(): readonly GraphQLDirective[];

Returns the current directive definition.

more
less

@param — - The GraphQL name to look up.

@returns — The current directive definition, if known.

@example — ```ts import { buildSchema } from 'graphql/utilities';

const schema = buildSchema(` directive

@upper — on FIELD_DEFINITION

type Query { greeting: String

@upper — } `);

schema.getDirective('upper')?.name; // => 'upper' schema.getDirective('missing'); // => undefined

getDirective(name: string): Maybe<GraphQLDirective>;

Returns a normalized configuration object for this object.

more
less

The returned config preserves the original assumeValid flag so the schema can be recreated with the same validation behavior.

@returns — A configuration object that can be used to recreate this object.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { GraphQLSchema } from 'graphql/type';

const schema = buildSchema( type Query { greeting: String });

const config = schema.toConfig(); const schemaCopy = new GraphQLSchema(config);

config.query?.name; // => 'Query' schemaCopy.getQueryType()?.name; // => 'Query'

toConfig(): GraphQLSchemaNormalizedConfig;
}
Referenced by
Unexported symbols referenced here

@internal —

interface GraphQLSchemaNormalizedConfig extends GraphQLSchemaConfig {
description: Maybe<string>;
types: readonly GraphQLNamedType[];
directives: readonly GraphQLDirective[];
extensions: Readonly<GraphQLSchemaExtensions>;
extensionASTNodes: readonly SchemaExtensionNode[];
assumeValid: boolean;
}
Referenced by

Directives are used by the GraphQL runtime as a way of modifying execution behavior. Type system creators will usually not create these directly.

export class GraphQLDirective {

Creates a GraphQLDirective instance.

more
less

@param — - Configuration describing this object.

@example — ```ts import { DirectiveLocation, parse } from 'graphql/language'; import { GraphQLBoolean, GraphQLDirective, GraphQLInt, GraphQLNonNull, } from 'graphql/type';

const document = parse(` directive

@cacheControl — (maxAge: Int) repeatable on FIELD_DEFINITION extend directive

@cacheControl — (maxAge: Int) on FIELD_DEFINITION `); const definition = document.definitions[0];

const cacheControl = new GraphQLDirective({ name: 'cacheControl', description: 'Controls HTTP cache hints for a field.', locations: [DirectiveLocation.FIELD_DEFINITION], args: { inheritMaxAge: { description: 'Inherit the parent cache hint.', type: new GraphQLNonNull(GraphQLBoolean), defaultValue: false, deprecationReason: 'Use maxAge instead.', extensions: { scope: 'cache' }, }, maxAge: { type: GraphQLInt, astNode: definition.arguments[0], }, }, isRepeatable: true, deprecationReason: 'Use

@cache — instead.', extensions: { scope: 'cache' }, astNode: definition, extensionASTNodes: [ document.definitions[1] ], });

cacheControl.name; // => 'cacheControl' cacheControl.description; // => 'Controls HTTP cache hints for a field.' cacheControl.args[0].name; // => 'inheritMaxAge' cacheControl.args[0].defaultValue; // => false cacheControl.isRepeatable; // => true cacheControl.extensions; // => { scope: 'cache' }

constructor(config: Readonly<GraphQLDirectiveConfig>)

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

Locations where this directive may be applied.

locations: readonly DirectiveLocation[];

Arguments accepted by this field or directive.

args: readonly GraphQLArgument[];

Whether this directive may appear more than once at the same location.

isRepeatable: boolean;

Reason this element is deprecated, if one was provided.

deprecationReason: Maybe<string>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLDirectiveExtensions>;

AST node from which this schema element was built, if available.

astNode: Maybe<DirectiveDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes: readonly DirectiveExtensionNode[];
get [Symbol.toStringTag](): string;

Returns a normalized configuration object for this object.

more
less

@returns — A configuration object that can be used to recreate this object.

@example — ```ts import { DirectiveLocation } from 'graphql/language'; import { GraphQLDirective, GraphQLString } from 'graphql/type';

const tag = new GraphQLDirective({ name: 'tag', locations: [DirectiveLocation.FIELD_DEFINITION], args: { name: { type: GraphQLString }, }, });

const config = tag.toConfig(); const tagCopy = new GraphQLDirective(config);

config.args.name.type; // => GraphQLString tagCopy.args[0].name; // => 'name'

toConfig(): GraphQLDirectiveNormalizedConfig;

Returns the schema coordinate identifying this directive.

more
less

@returns — The directive schema coordinate.

@example — ```ts import { DirectiveLocation } from 'graphql/language'; import { GraphQLDirective } from 'graphql/type';

const tag = new GraphQLDirective({ name: 'tag', locations: [DirectiveLocation.FIELD_DEFINITION], });

tag.toString(); // => '@tag'

toString(): string;

Returns the JSON representation used when this object is serialized.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { DirectiveLocation } from 'graphql/language'; import { GraphQLDirective } from 'graphql/type';

const tag = new GraphQLDirective({ name: 'tag', locations: [DirectiveLocation.FIELD_DEFINITION], });

tag.toJSON(); // => '@tag' JSON.stringify({ directive: tag }); // => '{"directive":"@tag"}'

toJSON(): string;
}
Referenced by
Unexported symbols referenced here
interface GraphQLDirectiveNormalizedConfig extends GraphQLDirectiveConfig {
isRepeatable: boolean;
extensions: Readonly<GraphQLDirectiveExtensions>;
extensionASTNodes: readonly DirectiveExtensionNode[];
}
Referenced by

Scalar Type Definition

more
less

Scalar types define the leaf values of a GraphQL response and the input values accepted by arguments and input object fields. A scalar type has a name and coercion functions that validate and convert runtime values and GraphQL literals.

If a type's serialize function returns null or does not return a value (i.e. it returns undefined) then an error will be raised and a null value will be returned in the response. Prefer validating inputs before execution so clients receive input diagnostics before result coercion fails.

@typeParam — TInternal - The internal runtime representation accepted by this scalar.

@typeParam — TExternal - The serialized representation exposed in GraphQL results.

@example — ```ts const OddType = new GraphQLScalarType({ name: 'Odd', serialize: (value) => { if (!Number.isFinite(value)) { throw new Error( Scalar "Odd" cannot represent "${value}" since it is not a finite number., ); }

if (value % 2 === 0) {
throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`);
}
return value;

} });

export class GraphQLScalarType<TInternal = unknown, TExternal = TInternal> {

Creates a GraphQLScalarType instance.

more
less

@param — - Configuration describing this object.

@example — ```ts import { Kind, parse } from 'graphql/language'; import { GraphQLScalarType } from 'graphql/type';

const document = parse(` "Odd integer values." scalar Odd

@specifiedBy — (url: "https://example.com/odd")

extend scalar Odd

@specifiedBy — (url: "https://example.com/odd-v2") `);

const Odd = new GraphQLScalarType({ name: 'Odd', description: 'Odd integer values.', specifiedByURL: 'https://example.com/odd', serialize: (value) => { if (typeof value !== 'number' || value % 2 === 0) { throw new TypeError('Odd can only serialize odd numbers.'); } return value; }, parseValue: (value) => { if (typeof value !== 'number' || value % 2 === 0) { throw new TypeError('Odd can only parse odd numbers.'); } return value; }, parseLiteral: (ast) => { if (ast.kind !== Kind.INT) { throw new TypeError('Odd can only parse integer literals.'); } const value = Number(ast.value); if (value % 2 === 0) { throw new TypeError('Odd can only parse odd integer literals.'); } return value; }, extensions: { numeric: true }, astNode: document.definitions[0], extensionASTNodes: [ document.definitions[1] ], });

Odd.description; // => 'Odd integer values.' Odd.specifiedByURL; // => 'https://example.com/odd' Odd.serialize(3); // => 3 Odd.parseValue(5); // => 5 Odd.extensions; // => { numeric: true }

constructor(config: Readonly<GraphQLScalarTypeConfig<TInternal, TExternal>>)

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

URL identifying the behavior specified for this custom scalar.

specifiedByURL: Maybe<string>;

Function that converts internal values to externally visible scalar values.

serialize: GraphQLScalarSerializer<TExternal>;

Function that converts variable input into this scalar's internal value.

parseValue: GraphQLScalarValueParser<TInternal>;

Function that converts AST input literals into this scalar's internal value.

parseLiteral: GraphQLScalarLiteralParser<TInternal>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLScalarTypeExtensions>;

AST node from which this schema element was built, if available.

astNode: Maybe<ScalarTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes: readonly ScalarTypeExtensionNode[];
get [Symbol.toStringTag](): string;

Returns a normalized configuration object for this object.

more
less

@returns — A configuration object that can be used to recreate this object.

@example — ```ts import { GraphQLScalarType } from 'graphql/type';

const Url = new GraphQLScalarType({ name: 'Url', description: 'An absolute URL string.', specifiedByURL: 'https://url.spec.whatwg.org/', });

const config = Url.toConfig(); const UrlCopy = new GraphQLScalarType(config);

config.name; // => 'Url' config.specifiedByURL; // => 'https://url.spec.whatwg.org/' UrlCopy.name; // => Url.name

toConfig(): GraphQLScalarTypeNormalizedConfig<TInternal, TExternal>;

Returns the schema coordinate identifying this scalar type.

more
less

@returns — The schema coordinate for this scalar type.

@example — ```ts import { GraphQLScalarType } from 'graphql/type';

const DateTime = new GraphQLScalarType({ name: 'DateTime' });

DateTime.toString(); // => 'DateTime' String(DateTime); // => 'DateTime'

toString(): string;

Returns the JSON representation used when this object is serialized.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { GraphQLScalarType } from 'graphql/type';

const DateTime = new GraphQLScalarType({ name: 'DateTime' });

DateTime.toJSON(); // => 'DateTime' JSON.stringify({ type: DateTime }); // => '{"type":"DateTime"}'

toJSON(): string;
}
Referenced by
Unexported symbols referenced here
interface GraphQLScalarTypeNormalizedConfig<TInternal, TExternal> extends GraphQLScalarTypeConfig<TInternal, TExternal> {
serialize: GraphQLScalarSerializer<TExternal>;
parseValue: GraphQLScalarValueParser<TInternal>;
parseLiteral: GraphQLScalarLiteralParser<TInternal>;
extensions: Readonly<GraphQLScalarTypeExtensions>;
extensionASTNodes: readonly ScalarTypeExtensionNode[];
}
Referenced by

Object Type Definition

more
less

Almost all of the GraphQL types you define will be object types. Object types have a name, but most importantly describe their fields.

@typeParam — TSource - Source object type passed to resolvers.

@typeParam — TContext - Context object type passed to resolvers.

@example — ```ts const AddressType = new GraphQLObjectType({ name: 'Address', fields: { street: { type: GraphQLString }, number: { type: GraphQLInt }, formatted: { type: GraphQLString, resolve: (obj) => { return obj.number + ' ' + obj.street } } } });

@example — When two types need to refer to each other, or a type needs to refer to
itself in a field, you can use a function expression (aka a closure or a
thunk) to supply the fields lazily.
```ts
const PersonType = new GraphQLObjectType({
name: 'Person',
fields: () => ({
name: { type: GraphQLString },
bestFriend: { type: PersonType },
})
});
export class GraphQLObjectType<TSource = any, TContext = any> {

Creates a GraphQLObjectType instance.

more
less

@param — - Configuration describing this object.

@example — ```ts // Configure an object type with interfaces, fields, arguments, and metadata. import { parse } from 'graphql/language'; import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull, GraphQLObjectType, GraphQLString, } from 'graphql/type';

const document = parse(` type User implements Node { id: ID! name(format: String = "short"): String }

extend type User { displayName: String } `); const definition = document.definitions[0]; const nameField = definition.fields[1]; const formatArg = nameField.arguments[0];

const Node = new GraphQLInterfaceType({ name: 'Node', fields: { id: { type: new GraphQLNonNull(GraphQLID) }, }, });

const User = new GraphQLObjectType({ name: 'User', description: 'A registered user.', interfaces: [Node], fields: { id: { type: new GraphQLNonNull(GraphQLID) }, name: { description: 'The formatted user name.', type: GraphQLString, args: { format: { description: 'Controls the name format.', type: GraphQLString, defaultValue: 'short', deprecationReason: 'Use locale instead.', extensions: { public: true }, astNode: formatArg, }, }, resolve: (user, { format }) => { return format === 'long' ? user.fullName : user.name; }, deprecationReason: 'Use displayName.', extensions: { cacheSeconds: 60 }, astNode: nameField, }, }, isTypeOf: (value) => { return typeof value === 'object' && value != null && 'id' in value; }, extensions: { entity: 'User' }, astNode: definition, extensionASTNodes: [ document.definitions[1] ], });

User.name; // => 'User' User.getInterfaces(); // => [Node] Object.keys(User.getFields()); // => ['id', 'name'] User.getFields().name.args[0].defaultValue; // => 'short' User.extensions; // => { entity: 'User' }

@example — ```ts
// This variant configures a subscription field with subscribe and resolve functions.
import { GraphQLObjectType, GraphQLString } from 'graphql/type';
const Subscription = new GraphQLObjectType({
name: 'Subscription',
fields: {
greeting: {
type: GraphQLString,
subscribe: async function* () {
yield { greeting: 'Hello!' };
},
resolve: (event) => {
return event.greeting;
},
},
},
});
typeof Subscription.getFields().greeting.subscribe; // => 'function'
constructor(config: Readonly<GraphQLObjectTypeConfig<TSource, TContext>>)

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

Predicate used to determine whether a runtime value belongs to this object type.

isTypeOf: Maybe<GraphQLIsTypeOfFn<TSource, TContext>>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLObjectTypeExtensions<TSource, TContext>>;

AST node from which this schema element was built, if available.

astNode: Maybe<ObjectTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes: readonly ObjectTypeExtensionNode[];
get [Symbol.toStringTag](): string;

Returns the fields defined by this type.

more
less

@returns — The fields keyed by field name.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertObjectType } from 'graphql/type';

const schema = buildSchema(` type User { id: ID! name: String }

type Query { viewer: User } `);

const User = assertObjectType(schema.getType('User')); const fields = User.getFields();

Object.keys(fields); // => ['id', 'name'] String(fields.id.type); // => 'ID!'

getFields(): GraphQLFieldMap<TSource, TContext>;

Returns the interfaces implemented by this type.

more
less

@returns — The implemented interfaces.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertObjectType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

type Query { viewer: User } `);

const User = assertObjectType(schema.getType('User'));

User.getInterfaces().map((type) => type.name); // => ['Node']

getInterfaces(): readonly GraphQLInterfaceType[];

Returns a normalized configuration object for this object.

more
less

@returns — A configuration object that can be used to recreate this object.

@example — ```ts import { GraphQLObjectType, GraphQLString } from 'graphql/type';

const User = new GraphQLObjectType({ name: 'User', fields: { name: { type: GraphQLString }, }, });

const config = User.toConfig(); const UserCopy = new GraphQLObjectType(config);

config.fields.name.type; // => GraphQLString UserCopy.getFields().name.type; // => GraphQLString

toConfig(): GraphQLObjectTypeNormalizedConfig<TSource, TContext>;

Returns the schema coordinate identifying this object type.

more
less

@returns — The schema coordinate for this object type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertObjectType } from 'graphql/type';

const schema = buildSchema(` type User { name: String }

type Query { viewer: User } `);

const User = assertObjectType(schema.getType('User'));

User.toString(); // => 'User'

toString(): string;

Returns the JSON representation used when this object is serialized.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { GraphQLObjectType, GraphQLString } from 'graphql/type';

const User = new GraphQLObjectType({ name: 'User', fields: { name: { type: GraphQLString } }, });

User.toJSON(); // => 'User' JSON.stringify({ type: User }); // => '{"type":"User"}'

toJSON(): string;
}
Referenced by
Unexported symbols referenced here
interface GraphQLObjectTypeNormalizedConfig<TSource, TContext> extends GraphQLObjectTypeConfig<any, any> {
interfaces: readonly GraphQLInterfaceType[];
fields: GraphQLFieldConfigMap<any, any>;
extensions: Readonly<GraphQLObjectTypeExtensions<TSource, TContext>>;
extensionASTNodes: readonly ObjectTypeExtensionNode[];
}
Referenced by

Interface Type Definition

more
less

When a field can return one of a heterogeneous set of types, a Interface type is used to describe what types are possible, what fields are in common across all types, as well as a function to determine which type is actually used when the field is resolved.

@example — ```ts const EntityType = new GraphQLInterfaceType({ name: 'Entity', fields: { name: { type: GraphQLString } } });

export class GraphQLInterfaceType {

Creates a GraphQLInterfaceType instance.

more
less

@param — - Configuration describing this object.

@example — ```ts import { parse } from 'graphql/language'; import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull } from 'graphql/type';

const document = parse(` interface Node { id: ID! }

interface Resource implements Node { id: ID! }

extend interface Resource { url: String } `);

const Node = new GraphQLInterfaceType({ name: 'Node', fields: { id: { type: new GraphQLNonNull(GraphQLID) }, }, });

const Resource = new GraphQLInterfaceType({ name: 'Resource', description: 'An addressable resource.', interfaces: [Node], fields: { id: { type: new GraphQLNonNull(GraphQLID) }, }, resolveType: (value) => { return typeof value === 'object' && value != null && 'url' in value ? 'WebPage' : null; }, extensions: { abstract: true }, astNode: document.definitions[1], extensionASTNodes: [ document.definitions[2] ], });

Resource.name; // => 'Resource' Resource.getInterfaces(); // => [Node] Object.keys(Resource.getFields()); // => ['id'] Resource.extensions; // => { abstract: true }

constructor(config: Readonly<GraphQLInterfaceTypeConfig<any, any>>)

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

Function that resolves the concrete object type for this abstract type.

resolveType: Maybe<GraphQLTypeResolver<any, any>>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLInterfaceTypeExtensions>;

AST node from which this schema element was built, if available.

astNode: Maybe<InterfaceTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes: readonly InterfaceTypeExtensionNode[];
get [Symbol.toStringTag](): string;

Returns the fields defined by this type.

more
less

@returns — The fields keyed by field name.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInterfaceType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

type Query { node: Node } `);

const Node = assertInterfaceType(schema.getType('Node')); const fields = Node.getFields();

Object.keys(fields); // => ['id'] String(fields.id.type); // => 'ID!'

getFields(): GraphQLFieldMap<any, any>;

Returns the interfaces implemented by this type.

more
less

@returns — The implemented interfaces.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInterfaceType } from 'graphql/type';

const schema = buildSchema(` interface Resource { url: String! }

interface Image implements Resource { url: String! width: Int }

type Photo implements Resource & Image { url: String! width: Int }

type Query { image: Image } `);

const Image = assertInterfaceType(schema.getType('Image'));

Image.getInterfaces().map((type) => type.name); // => ['Resource']

getInterfaces(): readonly GraphQLInterfaceType[];

Returns a normalized configuration object for this object.

more
less

@returns — A configuration object that can be used to recreate this object.

@example — ```ts import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull } from 'graphql/type';

const Node = new GraphQLInterfaceType({ name: 'Node', fields: { id: { type: new GraphQLNonNull(GraphQLID) }, }, });

const config = Node.toConfig(); const NodeCopy = new GraphQLInterfaceType(config);

String(config.fields.id.type); // => 'ID!' String(NodeCopy.getFields().id.type); // => 'ID!'

toConfig(): GraphQLInterfaceTypeNormalizedConfig;

Returns the schema coordinate identifying this interface type.

more
less

@returns — The schema coordinate for this interface type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInterfaceType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

type Query { node: Node } `);

const Node = assertInterfaceType(schema.getType('Node'));

Node.toString(); // => 'Node'

toString(): string;

Returns the JSON representation used when this object is serialized.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { GraphQLInterfaceType, GraphQLString } from 'graphql/type';

const Named = new GraphQLInterfaceType({ name: 'Named', fields: { name: { type: GraphQLString } }, });

Named.toJSON(); // => 'Named' JSON.stringify({ type: Named }); // => '{"type":"Named"}'

toJSON(): string;
}
Referenced by
Unexported symbols referenced here

@internal —

interface GraphQLInterfaceTypeNormalizedConfig extends GraphQLInterfaceTypeConfig<any, any> {
interfaces: readonly GraphQLInterfaceType[];
fields: GraphQLFieldConfigMap<any, any>;
extensions: Readonly<GraphQLInterfaceTypeExtensions>;
extensionASTNodes: readonly InterfaceTypeExtensionNode[];
}
Referenced by

Union Type Definition

more
less

When a field can return one of a heterogeneous set of types, a Union type is used to describe what types are possible as well as providing a function to determine which type is actually used when the field is resolved.

@example — ```ts const PetType = new GraphQLUnionType({ name: 'Pet', types: [DogType, CatType], resolveType: (value) => { if (value instanceof Dog) { return DogType; } if (value instanceof Cat) { return CatType; } } });

export class GraphQLUnionType {

Creates a GraphQLUnionType instance.

more
less

@param — - Configuration describing this object.

@example — ```ts import { parse } from 'graphql/language'; import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type';

const document = parse(` union Media = Photo | Video

extend union Media = Audio `);

const Photo = new GraphQLObjectType({ name: 'Photo', fields: { url: { type: GraphQLString } }, }); const Video = new GraphQLObjectType({ name: 'Video', fields: { url: { type: GraphQLString } }, });

const Media = new GraphQLUnionType({ name: 'Media', description: 'Media that can appear in a search result.', types: [Photo, Video], resolveType: (value) => { return typeof value === 'object' && value != null && 'duration' in value ? 'Video' : 'Photo'; }, extensions: { searchable: true }, astNode: document.definitions[0], extensionASTNodes: [ document.definitions[1] ], });

Media.description; // => 'Media that can appear in a search result.' Media.getTypes().map((type) => type.name); // => ['Photo', 'Video'] Media.extensions; // => { searchable: true }

constructor(config: Readonly<GraphQLUnionTypeConfig<any, any>>)

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

Function that resolves the concrete object type for this abstract type.

resolveType: Maybe<GraphQLTypeResolver<any, any>>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLUnionTypeExtensions>;

AST node from which this schema element was built, if available.

astNode: Maybe<UnionTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes: readonly UnionTypeExtensionNode[];
get [Symbol.toStringTag](): string;

Returns the object types included in this union.

more
less

@returns — The union member object types.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertUnionType } from 'graphql/type';

const schema = buildSchema(` type Photo { url: String! }

type Video { url: String! }

union Media = Photo | Video

type Query { media: [Media] } `);

const Media = assertUnionType(schema.getType('Media'));

Media.getTypes().map((type) => type.name); // => ['Photo', 'Video']

getTypes(): readonly GraphQLObjectType[];

Returns a normalized configuration object for this object.

more
less

@returns — A configuration object that can be used to recreate this object.

@example — ```ts import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type';

const Photo = new GraphQLObjectType({ name: 'Photo', fields: { url: { type: GraphQLString } }, }); const Video = new GraphQLObjectType({ name: 'Video', fields: { url: { type: GraphQLString } }, }); const Media = new GraphQLUnionType({ name: 'Media', types: [Photo, Video], });

const config = Media.toConfig(); const MediaCopy = new GraphQLUnionType(config);

MediaCopy.getTypes().map((type) => type.name); // => ['Photo', 'Video']

toConfig(): GraphQLUnionTypeNormalizedConfig;

Returns the schema coordinate identifying this union type.

more
less

@returns — The schema coordinate for this union type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertUnionType } from 'graphql/type';

const schema = buildSchema(` type Photo { url: String! }

union SearchResult = Photo

type Query { search: [SearchResult] } `);

const SearchResult = assertUnionType(schema.getType('SearchResult'));

SearchResult.toString(); // => 'SearchResult'

toString(): string;

Returns the JSON representation used when this object is serialized.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type';

const Photo = new GraphQLObjectType({ name: 'Photo', fields: { url: { type: GraphQLString } }, }); const SearchResult = new GraphQLUnionType({ name: 'SearchResult', types: [Photo], });

SearchResult.toJSON(); // => 'SearchResult' JSON.stringify({ type: SearchResult }); // => '{"type":"SearchResult"}'

toJSON(): string;
}
Referenced by
Unexported symbols referenced here
interface GraphQLUnionTypeNormalizedConfig extends GraphQLUnionTypeConfig<any, any> {
types: readonly GraphQLObjectType[];
extensions: Readonly<GraphQLUnionTypeExtensions>;
extensionASTNodes: readonly UnionTypeExtensionNode[];
}
Referenced by

Enum Type Definition

more
less

Enum types define leaf values whose serialized form is one of a fixed set of GraphQL enum names. Internally, enum values can map to any runtime value, often integers.

@example — ```ts import { GraphQLEnumType } from 'graphql/type';

const RGBType = new GraphQLEnumType({ name: 'RGB', values: { RED: { value: 0 }, GREEN: { value: 1 }, BLUE: { value: 2 }, }, });

RGBType.getValue('GREEN')?.value; // => 1

Note: If a value is not provided in a definition, the name of the enum value
will be used as its internal value.
export class GraphQLEnumType {

Creates a GraphQLEnumType instance.

more
less

@param — - Configuration describing this object.

@example — ```ts import { parse } from 'graphql/language'; import { GraphQLEnumType } from 'graphql/type';

const document = parse(` enum Episode { NEW_HOPE EMPIRE JEDI }

extend enum Episode { FORCE_AWAKENS } `); const definition = document.definitions[0];

const Episode = new GraphQLEnumType({ name: 'Episode', description: 'A Star Wars film episode.', values: { NEW_HOPE: { value: 4, description: 'Released in 1977.', extensions: { trilogy: 'original' }, astNode: definition.values[0], }, EMPIRE: { value: 5, astNode: definition.values[1] }, JEDI: { value: 6, deprecationReason: 'Use RETURN_OF_THE_JEDI.', astNode: definition.values[2], }, }, extensions: { catalog: 'films' }, astNode: definition, extensionASTNodes: [ document.definitions[1] ], });

Episode.description; // => 'A Star Wars film episode.' Episode.serialize(5); // => 'EMPIRE' Episode.parseValue('JEDI'); // => 6 Episode.getValue('JEDI').deprecationReason; // => 'Use RETURN_OF_THE_JEDI.' Episode.extensions; // => { catalog: 'films' }

constructor(config: Readonly<GraphQLEnumTypeConfig>)

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLEnumTypeExtensions>;

AST node from which this schema element was built, if available.

astNode: Maybe<EnumTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes: readonly EnumTypeExtensionNode[];
get [Symbol.toStringTag](): string;

Returns the values defined by this enum type.

more
less

@returns — Enum value definitions in schema order.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertEnumType } from 'graphql/type';

const schema = buildSchema(` enum Episode { NEW_HOPE EMPIRE JEDI }

type Query { episode: Episode } `);

const Episode = assertEnumType(schema.getType('Episode'));

Episode.getValues().map((value) => value.name); // => ['NEW_HOPE', 'EMPIRE', 'JEDI']

getValues(): readonly GraphQLEnumValue[];

Returns the enum value definition for a value name.

more
less

@param — - The GraphQL name to look up.

@returns — The matching enum value definition, if it exists.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertEnumType } from 'graphql/type';

const schema = buildSchema(` enum Episode { NEW_HOPE EMPIRE }

type Query { episode: Episode } `);

const Episode = assertEnumType(schema.getType('Episode'));

Episode.getValue('EMPIRE')?.name; // => 'EMPIRE' Episode.getValue('JEDI'); // => undefined

getValue(name: string): Maybe<GraphQLEnumValue>;

Serializes a runtime enum value as a GraphQL enum name.

more
less

@param — - Runtime enum value to serialize.

@returns — The GraphQL enum name for the runtime value.

@example — ```ts import { GraphQLEnumType } from 'graphql/type';

const RGB = new GraphQLEnumType({ name: 'RGB', values: { RED: { value: 0 }, GREEN: { value: 1 }, BLUE: { value: 2 }, }, });

RGB.serialize(1); // => 'GREEN' RGB.serialize(3); // throws an error

serialize(outputValue: unknown): Maybe<string>;

Parses a GraphQL enum name from variable input.

more
less

@param — - Runtime input value to parse.

@returns — The internal enum value represented by the input name.

@example — ```ts import { GraphQLEnumType } from 'graphql/type';

const RGB = new GraphQLEnumType({ name: 'RGB', values: { RED: { value: 0 }, GREEN: { value: 1 }, BLUE: { value: 2 }, }, });

RGB.parseValue('BLUE'); // => 2 RGB.parseValue('PURPLE'); // throws an error RGB.parseValue(2); // throws an error

parseValue(inputValue: unknown): Maybe<any>;

Parses a GraphQL enum name from an AST value literal.

more
less

@param — - AST value literal to parse.

@param — - Runtime variable values; ignored because enum literals cannot contain variables.

@returns — The internal enum value represented by the literal.

@example — ```ts import { parseValue } from 'graphql/language'; import { GraphQLEnumType } from 'graphql/type';

const RGB = new GraphQLEnumType({ name: 'RGB', values: { RED: { value: 0 }, GREEN: { value: 1 }, BLUE: { value: 2 }, }, });

RGB.parseLiteral(parseValue('RED')); // => 0 RGB.parseLiteral(parseValue('"RED"')); // throws an error

parseLiteral(valueNode: ValueNode, _variables: Maybe<ObjMap<unknown>>): Maybe<any>;

Returns a normalized configuration object for this object.

more
less

@returns — A configuration object that can be used to recreate this object.

@example — ```ts import { GraphQLEnumType } from 'graphql/type';

const RGB = new GraphQLEnumType({ name: 'RGB', values: { RED: { value: 0 }, GREEN: { value: 1 }, BLUE: { value: 2 }, }, });

const config = RGB.toConfig(); const RGBCopy = new GraphQLEnumType(config);

config.values.GREEN.value; // => 1 RGBCopy.serialize(2); // => 'BLUE'

toConfig(): GraphQLEnumTypeNormalizedConfig;

Returns the schema coordinate identifying this enum type.

more
less

@returns — The schema coordinate for this enum type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertEnumType } from 'graphql/type';

const schema = buildSchema(` enum Episode { NEW_HOPE }

type Query { episode: Episode } `);

const Episode = assertEnumType(schema.getType('Episode'));

Episode.toString(); // => 'Episode'

toString(): string;

Returns the JSON representation used when this object is serialized.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { GraphQLEnumType } from 'graphql/type';

const Episode = new GraphQLEnumType({ name: 'Episode', values: { NEW_HOPE: {}, }, });

Episode.toJSON(); // => 'Episode' JSON.stringify({ type: Episode }); // => '{"type":"Episode"}'

toJSON(): string;
}
Referenced by
Unexported symbols referenced here
interface GraphQLEnumTypeNormalizedConfig extends GraphQLEnumTypeConfig {
extensions: Readonly<GraphQLEnumTypeExtensions>;
extensionASTNodes: readonly EnumTypeExtensionNode[];
}
Referenced by

Input Object Type Definition

more
less

An input object defines a structured collection of fields which may be supplied to a field argument.

Using NonNull will ensure that a value must be provided by the query

@example — ```ts const GeoPoint = new GraphQLInputObjectType({ name: 'GeoPoint', fields: { lat: { type: new GraphQLNonNull(GraphQLFloat) }, lon: { type: new GraphQLNonNull(GraphQLFloat) }, alt: { type: GraphQLFloat, defaultValue: 0 }, } });

export class GraphQLInputObjectType {

Creates a GraphQLInputObjectType instance.

more
less

@param — - Configuration describing this object.

@example — ```ts import { parse } from 'graphql/language'; import { GraphQLID, GraphQLInputObjectType, GraphQLInt, GraphQLNonNull, GraphQLString, } from 'graphql/type';

const document = parse(` input ReviewInput { stars: Int! commentary: String }

extend input ReviewInput { body: String } `); const definition = document.definitions[0];

const ReviewInput = new GraphQLInputObjectType({ name: 'ReviewInput', description: 'Input collected when reviewing a product.', fields: { stars: { description: 'Star rating from one to five.', type: new GraphQLNonNull(GraphQLInt), extensions: { min: 1, max: 5 }, astNode: definition.fields[0], }, commentary: { type: GraphQLString, defaultValue: '', deprecationReason: 'Use body.', astNode: definition.fields[1], }, }, extensions: { form: 'review' }, astNode: definition, extensionASTNodes: [ document.definitions[1] ], isOneOf: false, }); const SearchBy = new GraphQLInputObjectType({ name: 'SearchBy', fields: { id: { type: GraphQLID }, slug: { type: GraphQLString }, }, isOneOf: true, });

const fields = ReviewInput.getFields();

ReviewInput.description; // => 'Input collected when reviewing a product.' String(fields.stars.type); // => 'Int!' fields.stars.extensions; // => { min: 1, max: 5 } fields.commentary.defaultValue; // => '' fields.commentary.deprecationReason; // => 'Use body.' ReviewInput.isOneOf; // => false SearchBy.isOneOf; // => true

constructor(config: Readonly<GraphQLInputObjectTypeConfig>)

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLInputObjectTypeExtensions>;

AST node from which this schema element was built, if available.

astNode: Maybe<InputObjectTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes: readonly InputObjectTypeExtensionNode[];

Whether this input object uses the experimental OneOf input object semantics.

isOneOf: boolean;
get [Symbol.toStringTag](): string;

Returns the fields defined by this type.

more
less

@returns — The fields keyed by field name.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInputObjectType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! commentary: String = "" }

type Query { reviews(filter: ReviewInput): [String] } `);

const ReviewInput = assertInputObjectType(schema.getType('ReviewInput')); const fields = ReviewInput.getFields();

Object.keys(fields); // => ['stars', 'commentary'] fields.commentary.defaultValue; // => ''

getFields(): GraphQLInputFieldMap;

Returns a normalized configuration object for this object.

more
less

@returns — A configuration object that can be used to recreate this object.

@example — ```ts import { GraphQLInputObjectType, GraphQLInt, GraphQLNonNull, } from 'graphql/type';

const ReviewInput = new GraphQLInputObjectType({ name: 'ReviewInput', fields: { stars: { type: new GraphQLNonNull(GraphQLInt) }, }, });

const config = ReviewInput.toConfig(); const ReviewInputCopy = new GraphQLInputObjectType(config);

String(config.fields.stars.type); // => 'Int!' String(ReviewInputCopy.getFields().stars.type); // => 'Int!'

toConfig(): GraphQLInputObjectTypeNormalizedConfig;

Returns the schema coordinate identifying this input object type.

more
less

@returns — The schema coordinate for this input object type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInputObjectType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! }

type Query { reviews(filter: ReviewInput): [String] } `);

const ReviewInput = assertInputObjectType(schema.getType('ReviewInput'));

ReviewInput.toString(); // => 'ReviewInput'

toString(): string;

Returns the JSON representation used when this object is serialized.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { GraphQLInputObjectType, GraphQLString } from 'graphql/type';

const ReviewInput = new GraphQLInputObjectType({ name: 'ReviewInput', fields: { commentary: { type: GraphQLString }, }, });

ReviewInput.toJSON(); // => 'ReviewInput' JSON.stringify({ type: ReviewInput }); // => '{"type":"ReviewInput"}'

toJSON(): string;
}
Referenced by
Unexported symbols referenced here
interface GraphQLInputObjectTypeNormalizedConfig extends GraphQLInputObjectTypeConfig {
extensions: Readonly<GraphQLInputObjectTypeExtensions>;
extensionASTNodes: readonly InputObjectTypeExtensionNode[];
}
Referenced by

List Type Wrapper

more
less

A list is a wrapping type which points to another type. Lists are often created within the context of defining the fields of an object type.

@typeParam — T - The GraphQL type wrapped by this list type.

@example — ```ts const PersonType = new GraphQLObjectType({ name: 'Person', fields: () => ({ parents: { type: new GraphQLList(PersonType) }, children: { type: new GraphQLList(PersonType) }, }) })

export class GraphQLList<T extends GraphQLType> {

Creates a GraphQLList instance.

more
less

@param — - The type to wrap.

@example — ```ts import { GraphQLList, GraphQLString } from 'graphql/type';

const stringList = new GraphQLList(GraphQLString);

stringList.ofType; // => GraphQLString String(stringList); // => '[String]'

constructor(ofType: T)

The type wrapped by this list or non-null type.

readonly ofType: T;
get [Symbol.toStringTag](): string;

Returns this wrapping type as a GraphQL type-reference string.

more
less

@returns — The GraphQL type-reference string.

@example — ```ts import { GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql/type';

const stringList = new GraphQLList(GraphQLString); const requiredStringList = new GraphQLList(new GraphQLNonNull(GraphQLString));

stringList.toString(); // => '[String]' requiredStringList.toString(); // => '[String!]'

toString(): string;

Returns the JSON representation used when this object is serialized.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { GraphQLList, GraphQLString } from 'graphql/type';

const stringList = new GraphQLList(GraphQLString);

stringList.toJSON(); // => '[String]' JSON.stringify({ type: stringList }); // => '{"type":"[String]"}'

toJSON(): string;
}
Referenced by

Non-Null Type Wrapper

more
less

A non-null is a wrapping type which points to another type. Non-null types enforce that their values are never null and can ensure an error is raised if this ever occurs during a request. It is useful for fields which you can make a strong guarantee on non-nullability, for example usually the id field of a database row will never be null.

@typeParam — T - The nullable GraphQL type wrapped by this non-null type.

@example — ```ts const RowType = new GraphQLObjectType({ name: 'Row', fields: () => ({ id: { type: new GraphQLNonNull(GraphQLString) }, }) })

Note: the enforcement of non-nullability occurs within the executor.
export class GraphQLNonNull<T extends GraphQLNullableType> {

Creates a GraphQLNonNull instance.

more
less

@param — - The type to wrap.

@example — ```ts import { GraphQLNonNull, GraphQLString } from 'graphql/type';

const requiredString = new GraphQLNonNull(GraphQLString);

requiredString.ofType; // => GraphQLString String(requiredString); // => 'String!'

constructor(ofType: T)

The type wrapped by this list or non-null type.

readonly ofType: T;
get [Symbol.toStringTag](): string;

Returns this wrapping type as a GraphQL type-reference string.

more
less

@returns — The GraphQL type-reference string.

@example — ```ts import { GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql/type';

const requiredString = new GraphQLNonNull(GraphQLString); const requiredStringList = new GraphQLNonNull( new GraphQLList(GraphQLString), );

requiredString.toString(); // => 'String!' requiredStringList.toString(); // => '[String]!'

toString(): string;

Returns the JSON representation used when this object is serialized.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { GraphQLNonNull, GraphQLString } from 'graphql/type';

const requiredString = new GraphQLNonNull(GraphQLString);

requiredString.toJSON(); // => 'String!' JSON.stringify({ type: requiredString }); // => '{"type":"String!"}'

toJSON(): string;
}
Referenced by

All built-in scalar types defined by the GraphQL specification.

export const specifiedScalarTypes: readonly GraphQLScalarType[] = ...

The built-in Int scalar type.

export const GraphQLInt: GraphQLScalarType<number, number> = ...

The built-in Float scalar type.

export const GraphQLFloat: GraphQLScalarType<number, number> = ...

The built-in String scalar type.

export const GraphQLString: GraphQLScalarType<string, string> = ...

The built-in Boolean scalar type.

export const GraphQLBoolean: GraphQLScalarType<boolean, boolean> = ...

The built-in ID scalar type.

export const GraphQLID: GraphQLScalarType<string, string> = ...

Maximum possible Int value as per GraphQL Spec (32-bit signed integer). n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1

export const GRAPHQL_MAX_INT: 2147483647 = ...

Minimum possible Int value as per GraphQL Spec (32-bit signed integer). n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1)

export const GRAPHQL_MIN_INT: -2147483648 = ...

Full list of stable directives specified by GraphQL.js.

export const specifiedDirectives: readonly GraphQLDirective[] = ...

Used to conditionally include fields or fragments.

export const GraphQLIncludeDirective: GraphQLDirective = ...

Used to conditionally skip (exclude) fields or fragments.

export const GraphQLSkipDirective: GraphQLDirective = ...

Used to declare element of a GraphQL schema as deprecated.

more
less

The optional reason argument defaults to DEFAULT_DEPRECATION_REASON.

export const GraphQLDeprecatedDirective: GraphQLDirective = ...

Used to provide a URL for specifying the behavior of custom scalar definitions.

export const GraphQLSpecifiedByDirective: GraphQLDirective = ...

Used to indicate an Input Object is a OneOf Input Object.

export const GraphQLOneOfDirective: GraphQLDirective = ...

The introspection enum describing the different kinds of GraphQL types.

more
less

@category — Introspection

export enum TypeKind {

A scalar type.

SCALAR = "SCALAR",

An object type.

OBJECT = "OBJECT",

An interface type.

INTERFACE = "INTERFACE",

A union type.

UNION = "UNION",

An enum type.

ENUM = "ENUM",

An input object type.

INPUT_OBJECT = "INPUT_OBJECT",

A list wrapper type.

LIST = "LIST",

A non-null wrapper type.

NON_NULL = "NON_NULL"
}

Constant string used for default reason for a deprecation.

export const DEFAULT_DEPRECATION_REASON: "No longer supported" = ...

All introspection types defined by the GraphQL specification.

export const introspectionTypes: readonly GraphQLNamedType[] = ...

The introspection type describing a GraphQL schema.

export const __Schema: GraphQLObjectType = ...

The introspection type describing a GraphQL directive.

export const __Directive: GraphQLObjectType = ...

The introspection enum describing directive locations.

export const __DirectiveLocation: GraphQLEnumType = ...

The introspection type describing GraphQL types.

export const __Type: GraphQLObjectType = ...

The introspection type describing object and interface fields.

export const __Field: GraphQLObjectType = ...

The introspection type describing arguments and input fields.

export const __InputValue: GraphQLObjectType = ...

The introspection type describing enum values.

export const __EnumValue: GraphQLObjectType = ...

The introspection enum describing GraphQL type kinds.

export const __TypeKind: GraphQLEnumType = ...

Note that these are GraphQLField and not GraphQLFieldConfig, so the format for args is different.

export const SchemaMetaFieldDef: GraphQLField<unknown, unknown> = ...

The __type meta field definition used by introspection.

export const TypeMetaFieldDef: GraphQLField<unknown, unknown> = ...

The __typename meta field definition used by execution and introspection.

export const TypeNameMetaFieldDef: GraphQLField<unknown, unknown> = ...

Test if the given value is a GraphQL schema.

more
less

@param — - Value to inspect.

@returns — True when the value is a GraphQLSchema.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { GraphQLString, isSchema } from 'graphql/type';

const schema = buildSchema( type Query { greeting: String });

isSchema(schema); // => true isSchema(GraphQLString); // => false

export function isSchema(schema: unknown): schema is GraphQLSchema

Test if the given value is a GraphQL directive.

more
less

@param — - Value to inspect.

@returns — True when the value is a GraphQLDirective.

@example — ```ts import { DirectiveLocation } from 'graphql/language'; import { GraphQLDirective, GraphQLString, isDirective } from 'graphql/type';

const upper = new GraphQLDirective({ name: 'upper', locations: [DirectiveLocation.FIELD_DEFINITION], });

isDirective(upper); // => true isDirective(GraphQLString); // => false

export function isDirective(directive: unknown): directive is GraphQLDirective

Returns true when the value is any GraphQL type.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is any GraphQL type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { GraphQLList, GraphQLString, isType } from 'graphql/type';

const schema = buildSchema( type Query { name: String });

isType(GraphQLString); // => true isType(new GraphQLList(GraphQLString)); // => true isType(schema.getType('Query')); // => true isType('String'); // => false

export function isType(type: unknown): type is GraphQLType

There are predicates for each kind of GraphQL type.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQLScalarType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isScalarType } from 'graphql/type';

const schema = buildSchema(` scalar DateTime

type Query { createdAt: DateTime } `);

isScalarType(schema.getType('DateTime')); // => true isScalarType(schema.getType('Query')); // => false

export function isScalarType(type: unknown): type is GraphQLScalarType

Returns true when the value is a GraphQLObjectType.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQLObjectType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isObjectType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! }

type User { name: String }

type Query { user: User } `);

isObjectType(schema.getType('User')); // => true isObjectType(schema.getType('ReviewInput')); // => false

export function isObjectType(type: unknown): type is GraphQLObjectType

Returns true when the value is a GraphQLInterfaceType.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQLInterfaceType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isInterfaceType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

type Query { node: Node } `);

isInterfaceType(schema.getType('Node')); // => true isInterfaceType(schema.getType('User')); // => false

export function isInterfaceType(type: unknown): type is GraphQLInterfaceType

Returns true when the value is a GraphQLUnionType.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQLUnionType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isUnionType } from 'graphql/type';

const schema = buildSchema(` type Photo { url: String! }

type Video { url: String! }

union Media = Photo | Video

type Query { media: [Media] } `);

isUnionType(schema.getType('Media')); // => true isUnionType(schema.getType('Photo')); // => false

export function isUnionType(type: unknown): type is GraphQLUnionType

Returns true when the value is a GraphQLEnumType.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQLEnumType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isEnumType } from 'graphql/type';

const schema = buildSchema(` enum Episode { NEW_HOPE EMPIRE }

type Query { favoriteEpisode: Episode } `);

isEnumType(schema.getType('Episode')); // => true isEnumType(schema.getType('Query')); // => false

export function isEnumType(type: unknown): type is GraphQLEnumType

Returns true when the value is a GraphQLInputObjectType.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQLInputObjectType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isInputObjectType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! }

type Review { stars: Int! }

type Query { review(input: ReviewInput): Review } `);

isInputObjectType(schema.getType('ReviewInput')); // => true isInputObjectType(schema.getType('Review')); // => false

export function isInputObjectType(type: unknown): type is GraphQLInputObjectType

Returns true when the value is a GraphQLList.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQLList.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { GraphQLList, GraphQLString, isListType } from 'graphql/type';

const schema = buildSchema( type Query { tags: [String!]! });

const tagsField = schema.getQueryType()?.getFields().tags;

isListType(new GraphQLList(GraphQLString)); // => true isListType(GraphQLString); // => false isListType(tagsField?.type); // => false

export function isListType(type: GraphQLInputType): type is GraphQLList<GraphQLInputType>

Returns true when the output type is a GraphQLList.

more
less

@param — - The GraphQL output type to inspect.

@returns — True when the output type is a list type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { getNullableType, isListType } from 'graphql/type';

const schema = buildSchema( type Query { tags: [String!]! });

const tagsField = schema.getQueryType()?.getFields().tags; const nullableTagsType = getNullableType(tagsField?.type);

isListType(nullableTagsType); // => true

export function isListType(type: GraphQLOutputType): type is GraphQLList<GraphQLOutputType>

Returns true when the value is a GraphQLList.

more
less

@param — - The value to inspect.

@returns — True when the value is a list type.

@example — ```ts import { isListType } from 'graphql/type';

isListType('[String]'); // => false isListType(null); // => false

export function isListType(type: unknown): type is GraphQLList<GraphQLType>

Returns true when the value is a GraphQLNonNull.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQLNonNull.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { GraphQLNonNull, GraphQLString, isNonNullType } from 'graphql/type';

const schema = buildSchema( type Query { name: String! nickname: String });

const fields = schema.getQueryType()?.getFields();

isNonNullType(new GraphQLNonNull(GraphQLString)); // => true isNonNullType(fields?.name.type); // => true isNonNullType(fields?.nickname.type); // => false

export function isNonNullType(type: GraphQLInputType): type is GraphQLNonNull<GraphQLInputType>

Returns true when the output type is a GraphQLNonNull.

more
less

@param — - The GraphQL output type to inspect.

@returns — True when the output type is a non-null type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isNonNullType } from 'graphql/type';

const schema = buildSchema( type Query { name: String! nickname: String });

const fields = schema.getQueryType()?.getFields();

isNonNullType(fields?.name.type); // => true isNonNullType(fields?.nickname.type); // => false

export function isNonNullType(type: GraphQLOutputType): type is GraphQLNonNull<GraphQLOutputType>

Returns true when the value is a GraphQLNonNull.

more
less

@param — - The value to inspect.

@returns — True when the value is a non-null type.

@example — ```ts import { isNonNullType } from 'graphql/type';

isNonNullType('String!'); // => false isNonNullType(null); // => false

export function isNonNullType(type: unknown): type is GraphQLNonNull<GraphQLType>

Returns true when the value can be used as a GraphQL input type.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value can be used as a GraphQL input type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isInputType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! }

type Review { stars: Int! }

type Query { review(input: ReviewInput): Review } `);

isInputType(schema.getType('ReviewInput')); // => true isInputType(schema.getType('Review')); // => false

export function isInputType(type: unknown): type is GraphQLInputType

Returns true when the value can be used as a GraphQL output type.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value can be used as a GraphQL output type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isOutputType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! }

type Review { stars: Int! }

type Query { review(input: ReviewInput): Review } `);

isOutputType(schema.getType('Review')); // => true isOutputType(schema.getType('ReviewInput')); // => false

export function isOutputType(type: unknown): type is GraphQLOutputType

Returns true when the value is a GraphQL scalar or enum type.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQL scalar or enum type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isLeafType } from 'graphql/type';

const schema = buildSchema(` enum Episode { NEW_HOPE }

type Review { stars: Int! }

type Query { episode: Episode review: Review } `);

isLeafType(schema.getType('Episode')); // => true isLeafType(schema.getType('String')); // => true isLeafType(schema.getType('Review')); // => false

export function isLeafType(type: unknown): type is GraphQLLeafType

Returns true when the value is a GraphQL object, interface, or union type.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQL object, interface, or union type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isCompositeType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

union SearchResult = User

type Query { node: Node search: [SearchResult] } `);

isCompositeType(schema.getType('User')); // => true isCompositeType(schema.getType('Node')); // => true isCompositeType(schema.getType('SearchResult')); // => true isCompositeType(schema.getType('String')); // => false

export function isCompositeType(type: unknown): type is GraphQLCompositeType

Returns true when the value is a GraphQL interface or union type.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQL interface or union type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { isAbstractType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

union SearchResult = User

type Query { node: Node search: [SearchResult] } `);

isAbstractType(schema.getType('Node')); // => true isAbstractType(schema.getType('SearchResult')); // => true isAbstractType(schema.getType('User')); // => false

export function isAbstractType(type: unknown): type is GraphQLAbstractType

Returns true when the value is a GraphQL list or non-null wrapper type.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQL list or non-null wrapper type.

@example — ```ts import { GraphQLList, GraphQLNonNull, GraphQLString, isWrappingType, } from 'graphql/type';

isWrappingType(new GraphQLList(GraphQLString)); // => true isWrappingType(new GraphQLNonNull(GraphQLString)); // => true isWrappingType(GraphQLString); // => false

export function isWrappingType(type: unknown): type is GraphQLWrappingType

Returns true when the value is a GraphQL type that can accept null.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQL type that can accept null.

@example — ```ts import { GraphQLNonNull, GraphQLString, isNullableType } from 'graphql/type';

isNullableType(GraphQLString); // => true isNullableType(new GraphQLNonNull(GraphQLString)); // => false isNullableType(null); // => false

export function isNullableType(type: unknown): type is GraphQLNullableType

Returns true when the value is a GraphQL named type.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the value is a GraphQL named type.

@example — ```ts import { GraphQLList, GraphQLString, isNamedType } from 'graphql/type';

isNamedType(GraphQLString); // => true isNamedType(new GraphQLList(GraphQLString)); // => false isNamedType(null); // => false

export function isNamedType(type: unknown): type is GraphQLNamedType

Returns true when the argument is non-null and has no default value.

more
less

@param — - The argument definition to inspect.

@returns — True when the argument is non-null and has no default value.

@example — ```ts import { GraphQLInt, GraphQLNonNull, GraphQLString, isRequiredArgument, } from 'graphql/type';

const requiredArgument = { name: 'id', type: new GraphQLNonNull(GraphQLInt) }; const optionalArgument = { name: 'name', type: GraphQLString }; const argumentWithDefault = { name: 'limit', type: new GraphQLNonNull(GraphQLInt), defaultValue: 10, };

isRequiredArgument(requiredArgument); // => true isRequiredArgument(optionalArgument); // => false isRequiredArgument(argumentWithDefault); // => false

export function isRequiredArgument(arg: GraphQLArgument): boolean

Returns true when the input field is non-null and has no default value.

more
less

@param — - The input field definition to inspect.

@returns — True when the input field is non-null and has no default value.

@example — ```ts import { GraphQLInt, GraphQLNonNull, GraphQLString, isRequiredInputField, } from 'graphql/type';

const requiredField = { name: 'id', type: new GraphQLNonNull(GraphQLInt) }; const optionalField = { name: 'name', type: GraphQLString }; const fieldWithDefault = { name: 'limit', type: new GraphQLNonNull(GraphQLInt), defaultValue: 10, };

isRequiredInputField(requiredField); // => true isRequiredInputField(optionalField); // => false isRequiredInputField(fieldWithDefault); // => false

export function isRequiredInputField(field: GraphQLInputField): boolean

Returns true when the scalar type is one of the scalars specified by GraphQL.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the scalar type is one of the scalars specified by GraphQL.

@example — ```ts import { GraphQLScalarType, GraphQLString, isSpecifiedScalarType, } from 'graphql/type';

const DateTime = new GraphQLScalarType({ name: 'DateTime', });

isSpecifiedScalarType(GraphQLString); // => true isSpecifiedScalarType(DateTime); // => false

export function isSpecifiedScalarType(type: GraphQLNamedType): boolean

Returns true when the type is one of the built-in introspection types.

more
less

@param — - The GraphQL type to inspect.

@returns — True when the type is one of the built-in introspection types.

@example — ```ts import { GraphQLString, isIntrospectionType, __Type } from 'graphql/type';

isIntrospectionType(__Type); // => true isIntrospectionType(GraphQLString); // => false

export function isIntrospectionType(type: GraphQLNamedType): boolean

Returns true when the directive is one of the directives specified by GraphQL.

more
less

@param — - Directive to inspect.

@returns — True when the directive is specified by GraphQL.

@example — ```ts import { GraphQLDirective, GraphQLIncludeDirective, isSpecifiedDirective, } from 'graphql/type'; import { DirectiveLocation } from 'graphql/language';

const customDirective = new GraphQLDirective({ name: 'auth', locations: [DirectiveLocation.FIELD_DEFINITION], });

isSpecifiedDirective(GraphQLIncludeDirective); // => true isSpecifiedDirective(customDirective); // => false

export function isSpecifiedDirective(directive: GraphQLDirective): boolean

Returns the value as a GraphQLSchema, or throws if it is not a schema.

more
less

@param — - GraphQL schema to use.

@returns — The value typed as a GraphQLSchema.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertSchema, GraphQLString } from 'graphql/type';

const schema = buildSchema( type Query { greeting: String });

assertSchema(schema); // => schema assertSchema(GraphQLString); // throws an error

export function assertSchema(schema: unknown): GraphQLSchema

Returns the value as a GraphQLDirective, or throws if it is not a directive.

more
less

@param — - Value to inspect.

@returns — The value typed as a GraphQLDirective.

@example — ```ts import { DirectiveLocation } from 'graphql/language'; import { assertDirective, GraphQLDirective, GraphQLString } from 'graphql/type';

const upper = new GraphQLDirective({ name: 'upper', locations: [DirectiveLocation.FIELD_DEFINITION], });

assertDirective(upper); // => upper assertDirective(GraphQLString); // throws an error

export function assertDirective(directive: unknown): GraphQLDirective

Returns the value as a GraphQL type, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQL type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertType } from 'graphql/type';

const schema = buildSchema( type Query { name: String });

const queryType = assertType(schema.getType('Query'));

queryType.toString(); // => 'Query' assertType('Query'); // throws an error

export function assertType(type: unknown): GraphQLType

Returns the value as a GraphQLScalarType, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQLScalarType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertScalarType } from 'graphql/type';

const schema = buildSchema(` scalar DateTime

type Query { createdAt: DateTime } `);

const dateTimeType = assertScalarType(schema.getType('DateTime'));

dateTimeType.name; // => 'DateTime' assertScalarType(schema.getType('Query')); // throws an error

export function assertScalarType(type: unknown): GraphQLScalarType

Returns the value as a GraphQLObjectType, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQLObjectType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertObjectType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! }

type User { name: String }

type Query { user: User } `);

const userType = assertObjectType(schema.getType('User'));

Object.keys(userType.getFields()); // => ['name'] assertObjectType(schema.getType('ReviewInput')); // throws an error

export function assertObjectType(type: unknown): GraphQLObjectType

Returns the value as a GraphQLInterfaceType, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQLInterfaceType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInterfaceType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

type Query { node: Node } `);

const nodeType = assertInterfaceType(schema.getType('Node'));

nodeType.name; // => 'Node' assertInterfaceType(schema.getType('User')); // throws an error

export function assertInterfaceType(type: unknown): GraphQLInterfaceType

Returns the value as a GraphQLUnionType, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQLUnionType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertUnionType } from 'graphql/type';

const schema = buildSchema(` type Photo { url: String! }

type Video { url: String! }

union Media = Photo | Video

type Query { media: [Media] } `);

const mediaType = assertUnionType(schema.getType('Media'));

mediaType.getTypes().map((type) => type.name); // => ['Photo', 'Video'] assertUnionType(schema.getType('Photo')); // throws an error

export function assertUnionType(type: unknown): GraphQLUnionType

Returns the value as a GraphQLEnumType, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQLEnumType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertEnumType } from 'graphql/type';

const schema = buildSchema(` enum Episode { NEW_HOPE EMPIRE }

type Query { favoriteEpisode: Episode } `);

const episodeType = assertEnumType(schema.getType('Episode'));

episodeType.getValues().map((value) => value.name); // => ['NEW_HOPE', 'EMPIRE'] assertEnumType(schema.getType('Query')); // throws an error

export function assertEnumType(type: unknown): GraphQLEnumType

Returns the value as a GraphQLInputObjectType, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQLInputObjectType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInputObjectType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! }

type Review { stars: Int! }

type Query { review(input: ReviewInput): Review } `);

const inputType = assertInputObjectType(schema.getType('ReviewInput'));

Object.keys(inputType.getFields()); // => ['stars'] assertInputObjectType(schema.getType('Review')); // throws an error

export function assertInputObjectType(type: unknown): GraphQLInputObjectType

Returns the value as a GraphQLList, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQLList.

@example — ```ts import { GraphQLList, GraphQLString, assertListType } from 'graphql/type';

const listType = assertListType(new GraphQLList(GraphQLString));

listType.ofType; // => GraphQLString assertListType(GraphQLString); // throws an error

export function assertListType(type: unknown): GraphQLList<GraphQLType>

Returns the value as a GraphQLNonNull, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQLNonNull.

@example — ```ts import { GraphQLNonNull, GraphQLString, assertNonNullType } from 'graphql/type';

const nonNullType = assertNonNullType(new GraphQLNonNull(GraphQLString));

nonNullType.ofType; // => GraphQLString assertNonNullType(GraphQLString); // throws an error

export function assertNonNullType(type: unknown): GraphQLNonNull<GraphQLType>

Returns the value as a GraphQL input type, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQL input type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertInputType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! }

type Review { stars: Int! }

type Query { review(input: ReviewInput): Review } `);

const inputType = assertInputType(schema.getType('ReviewInput'));

inputType.toString(); // => 'ReviewInput' assertInputType(schema.getType('Review')); // throws an error

export function assertInputType(type: unknown): GraphQLInputType

Returns the value as a GraphQL output type, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQL output type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertOutputType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! }

type Review { stars: Int! }

type Query { review(input: ReviewInput): Review } `);

const outputType = assertOutputType(schema.getType('Review'));

outputType.toString(); // => 'Review' assertOutputType(schema.getType('ReviewInput')); // throws an error

export function assertOutputType(type: unknown): GraphQLOutputType

Returns the value as a GraphQL leaf type, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQL leaf type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertLeafType } from 'graphql/type';

const schema = buildSchema(` enum Episode { NEW_HOPE }

type Review { stars: Int! }

type Query { episode: Episode review: Review } `);

const episodeType = assertLeafType(schema.getType('Episode'));

episodeType.toString(); // => 'Episode' assertLeafType(schema.getType('Review')); // throws an error

export function assertLeafType(type: unknown): GraphQLLeafType

Returns the value as a GraphQL composite type, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQL composite type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertCompositeType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

type Query { node: Node } `);

const userType = assertCompositeType(schema.getType('User'));

userType.toString(); // => 'User' assertCompositeType(schema.getType('String')); // throws an error

export function assertCompositeType(type: unknown): GraphQLCompositeType

Returns the value as a GraphQL abstract type, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQL abstract type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertAbstractType } from 'graphql/type';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

type Query { node: Node } `);

const nodeType = assertAbstractType(schema.getType('Node'));

nodeType.toString(); // => 'Node' assertAbstractType(schema.getType('User')); // throws an error

export function assertAbstractType(type: unknown): GraphQLAbstractType

Returns the value as a GraphQL wrapping type, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQL wrapping type.

@example — ```ts import { GraphQLList, GraphQLString, assertWrappingType } from 'graphql/type';

const wrappingType = assertWrappingType(new GraphQLList(GraphQLString));

wrappingType.toString(); // => '[String]' assertWrappingType(GraphQLString); // throws an error

export function assertWrappingType(type: unknown): GraphQLWrappingType

Returns the value as a nullable GraphQL type, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a nullable GraphQL type.

@example — ```ts import { GraphQLNonNull, GraphQLString, assertNullableType, } from 'graphql/type';

const nullableType = assertNullableType(GraphQLString);

nullableType; // => GraphQLString assertNullableType(new GraphQLNonNull(GraphQLString)); // throws an error

export function assertNullableType(type: unknown): GraphQLNullableType

Returns the value as a GraphQL named type, or throws if it is not one.

more
less

@param — - The GraphQL type to inspect.

@returns — The value typed as a GraphQL named type.

@example — ```ts import { GraphQLList, GraphQLString, assertNamedType } from 'graphql/type';

const namedType = assertNamedType(GraphQLString);

namedType.name; // => 'String' assertNamedType(new GraphQLList(GraphQLString)); // throws an error

export function assertNamedType(type: unknown): GraphQLNamedType

Returns the nullable type.

more
less

@param — - The GraphQL type to inspect.

@returns — The nullable type after removing one non-null wrapper, if present.

@example — ```ts import { getNullableType } from 'graphql/type';

getNullableType(null); // => undefined getNullableType(undefined); // => undefined

export function getNullableType(type: undefined | null): void

Returns the nullable type after removing one non-null wrapper.

more
less

@param — - A nullable type or non-null wrapper.

@returns — The nullable type after removing one non-null wrapper, if present.

@typeParam — T - The nullable GraphQL type returned after removing one non-null wrapper.

@example — ```ts import { GraphQLList, GraphQLNonNull, GraphQLString, getNullableType, } from 'graphql/type';

const requiredString = new GraphQLNonNull(GraphQLString); const stringList = new GraphQLList(GraphQLString);

getNullableType(requiredString); // => GraphQLString getNullableType(stringList); // => stringList

export function getNullableType<T extends GraphQLNullableType>(type: T | GraphQLNonNull<T>): T

Returns the nullable type after removing one non-null wrapper.

more
less

@param — - The GraphQL type to inspect.

@returns — The nullable type after removing one non-null wrapper, if present.

@example — ```ts import { GraphQLList, GraphQLNonNull, GraphQLString, getNullableType, } from 'graphql/type';

const requiredStringList = new GraphQLNonNull( new GraphQLList(GraphQLString), );

getNullableType(requiredStringList).toString(); // => '[String]' getNullableType(GraphQLString); // => GraphQLString

export function getNullableType(type: Maybe<GraphQLType>): GraphQLNullableType | undefined

Returns the named type.

more
less

@param — - The GraphQL type to inspect.

@returns — The named type after unwrapping all list and non-null wrappers.

@example — ```ts import { getNamedType } from 'graphql/type';

getNamedType(null); // => undefined getNamedType(undefined); // => undefined

export function getNamedType(type: undefined | null): void

Returns the named input type after unwrapping all list and non-null wrappers.

more
less

@param — - The GraphQL input type to inspect.

@returns — The named input type after unwrapping all wrappers.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { getNamedType } from 'graphql/type';

const schema = buildSchema(` input ReviewInput { stars: Int! }

type Query { review(input: [ReviewInput!]!): Boolean } `);

const inputArg = schema.getQueryType()?.getFields().review.args[0];

getNamedType(inputArg?.type).toString(); // => 'ReviewInput'

export function getNamedType(type: GraphQLInputType): GraphQLNamedInputType

Returns the named output type after unwrapping all list and non-null wrappers.

more
less

@param — - The GraphQL output type to inspect.

@returns — The named output type after unwrapping all wrappers.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { getNamedType } from 'graphql/type';

const schema = buildSchema(` type User { name: String }

type Query { users: [User!]! } `);

const usersField = schema.getQueryType()?.getFields().users;

getNamedType(usersField?.type).toString(); // => 'User'

export function getNamedType(type: GraphQLOutputType): GraphQLNamedOutputType

Returns the named type after unwrapping all list and non-null wrappers.

more
less

@param — - The GraphQL type to inspect.

@returns — The named type after unwrapping all wrappers.

@example — ```ts import { GraphQLList, GraphQLNonNull, GraphQLString, getNamedType, } from 'graphql/type';

const nestedType = new GraphQLNonNull( new GraphQLList(new GraphQLNonNull(GraphQLString)), );

getNamedType(nestedType); // => GraphQLString

export function getNamedType(type: GraphQLType): GraphQLNamedType

Returns the named type after unwrapping all list and non-null wrappers.

more
less

@param — - The GraphQL type to inspect.

@returns — The named type after unwrapping all wrappers, or undefined for nullish input.

@example — ```ts import { GraphQLList, GraphQLString, getNamedType, } from 'graphql/type';

getNamedType(new GraphQLList(GraphQLString)); // => GraphQLString getNamedType(undefined); // => undefined

export function getNamedType(type: Maybe<GraphQLType>): GraphQLNamedType | undefined

Implements the "Type Validation" sub-sections of the specification's "Type System" section.

more
less

Validation runs synchronously, returning an array of encountered errors, or an empty array if no errors were encountered and the Schema is valid.

@param — - GraphQL schema to use.

@returns — Schema validation errors, or an empty array when the schema is valid.

@example — ```ts import { validateSchema } from 'graphql/type'; import { buildSchema } from 'graphql/utilities';

const schema = buildSchema( type Query { name: String }); const errors = validateSchema(schema);

errors; // => []

export function validateSchema(schema: GraphQLSchema): readonly GraphQLError[]

Utility function which asserts a schema is valid by throwing an error if it is invalid.

more
less

@param — - GraphQL schema to use.

@example — ```ts import { assertValidSchema } from 'graphql/type'; import { buildSchema } from 'graphql/utilities';

const schema = buildSchema( type Query { name: String });

assertValidSchema(schema); // does not throw

export function assertValidSchema(schema: GraphQLSchema): void

@category — Names

more
less

Upholds the spec rules about naming.

@param — - The GraphQL name to validate.

@returns — The validated GraphQL name.

@example — ```ts import { assertName } from 'graphql/type';

assertName('User'); // => 'User' assertName('123User'); // throws an error

export function assertName(name: string): string

Upholds the spec rules about naming enum values.

more
less

@param — - The GraphQL name to validate.

@returns — The validated GraphQL name.

@example — ```ts import { assertEnumValueName } from 'graphql/type';

assertEnumValueName('ACTIVE'); // => 'ACTIVE' assertEnumValueName('true'); // throws an error

export function assertEnumValueName(name: string): string

These types may describe types which may be leaf values.

export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType
Referenced by

These types may describe the parent context of a selection set.

export type GraphQLCompositeType = GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType
Referenced by

These types may describe the parent context of a selection set.

export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType
Referenced by

These types wrap and modify other types

export type GraphQLWrappingType = GraphQLList<GraphQLType> | GraphQLNonNull<GraphQLType>
Referenced by

A named GraphQL type that can be used as an input type.

export type GraphQLNamedInputType = GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType
Referenced by

A named GraphQL type that can be used as an output type.

export type GraphQLNamedOutputType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType
Referenced by

Used while defining GraphQL types to allow for circular references in otherwise immutable type definitions.

more
less

@typeParam — T - The element type returned by the thunk or array.

export type ThunkReadonlyArray<T> = (() => readonly T[]) | readonly T[]
Referenced by

A thunk that resolves to an object map.

more
less

@typeParam — T - Value type stored in the object map.

export type ThunkObjMap<T> = (() => ObjMap<T>) | ObjMap<T>
Referenced by

Configuration used to construct a GraphQLSchema.

export interface GraphQLSchemaConfig extends GraphQLSchemaValidationOptions {

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

Root object type for query operations.

query?: Maybe<GraphQLObjectType>;

Root object type for mutation operations.

mutation?: Maybe<GraphQLObjectType>;

Root object type for subscription operations.

subscription?: Maybe<GraphQLObjectType>;

Object types that belong to this union type.

types?: Maybe<readonly GraphQLNamedType[]>;

Directives available in this schema or applied to this AST node.

directives?: Maybe<readonly GraphQLDirective[]>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLSchemaExtensions>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<SchemaDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes?: Maybe<readonly SchemaExtensionNode[]>;
}
Referenced by
Unexported symbols referenced here

@internal —

interface GraphQLSchemaValidationOptions {

When building a schema from a GraphQL service's introspection result, it might be safe to assume the schema is valid. Set to true to assume the produced schema is valid.

more
less

Default: false

assumeValid?: boolean;
}
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLSchemaExtensions {
[key: string]: unknown;
}
Referenced by

Configuration used to construct a GraphQLDirective.

export interface GraphQLDirectiveConfig {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

Locations where this directive may be applied.

locations: readonly DirectiveLocation[];

Arguments accepted by this field or directive.

args?: Maybe<GraphQLFieldConfigArgumentMap>;

Whether this directive may appear more than once at the same location.

isRepeatable?: Maybe<boolean>;

Reason this element is deprecated, if one was provided.

deprecationReason?: Maybe<string>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLDirectiveExtensions>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<DirectiveDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes?: Maybe<readonly DirectiveExtensionNode[]>;
}
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLDirectiveExtensions {
[key: string]: unknown;
}
Referenced by

A resolved GraphQL argument definition.

export interface GraphQLArgument {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

The GraphQL type reference or runtime type for this element.

type: GraphQLInputType;

Default value used when no explicit value is supplied.

defaultValue: unknown;

Reason this element is deprecated, if one was provided.

deprecationReason: Maybe<string>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLArgumentExtensions>;

AST node from which this schema element was built, if available.

astNode: Maybe<InputValueDefinitionNode>;
}
Referenced by

Configuration used to define a GraphQL argument.

export interface GraphQLArgumentConfig {

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

The GraphQL type reference or runtime type for this element.

type: GraphQLInputType;

Default value used when no explicit value is supplied.

defaultValue?: unknown;

Reason this element is deprecated, if one was provided.

deprecationReason?: Maybe<string>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLArgumentExtensions>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<InputValueDefinitionNode>;
}
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLArgumentExtensions {
[key: string]: unknown;
}
Referenced by

Configuration used to construct a GraphQLEnumType.

export interface GraphQLEnumTypeConfig {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

Values contained in this enum, list, or input-object definition.

values: ThunkObjMap<GraphQLEnumValueConfig>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLEnumTypeExtensions>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<EnumTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes?: Maybe<readonly EnumTypeExtensionNode[]>;
}
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLEnumTypeExtensions {
[key: string]: unknown;
}
Referenced by

A resolved GraphQL enum value definition.

export interface GraphQLEnumValue {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

Parsed value represented by this node.

value: any;

Reason this element is deprecated, if one was provided.

deprecationReason: Maybe<string>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLEnumValueExtensions>;

AST node from which this schema element was built, if available.

astNode: Maybe<EnumValueDefinitionNode>;
}
Referenced by

Configuration used to define a GraphQL enum value.

export interface GraphQLEnumValueConfig {

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

Parsed value represented by this node.

value?: any;

Reason this element is deprecated, if one was provided.

deprecationReason?: Maybe<string>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLEnumValueExtensions>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<EnumValueDefinitionNode>;
}
Referenced by

A map of enum value names to enum value configuration objects.

export type GraphQLEnumValueConfigMap = ObjMap<GraphQLEnumValueConfig>

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLEnumValueExtensions {
[key: string]: unknown;
}
Referenced by

A resolved GraphQL field definition.

more
less

@typeParam — TSource - Source object type passed to resolvers.

@typeParam — TContext - Context object type passed to resolvers.

@typeParam — TArgs - Argument object type passed to resolvers.

export interface GraphQLField<TSource, TContext, TArgs = any> {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

The GraphQL type reference or runtime type for this element.

type: GraphQLOutputType;

Arguments accepted by this field or directive.

args: readonly GraphQLArgument[];

Resolver function used to produce this field value.

resolve?: GraphQLFieldResolver<TSource, TContext, TArgs>;

Resolver function used to create a subscription event stream for this field.

subscribe?: GraphQLFieldResolver<TSource, TContext, TArgs>;

Reason this element is deprecated, if one was provided.

deprecationReason: Maybe<string>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLFieldExtensions<TSource, TContext, TArgs>>;

AST node from which this schema element was built, if available.

astNode: Maybe<FieldDefinitionNode>;
}
Referenced by

Configuration used to define a GraphQL field.

more
less

@typeParam — TSource - Source object type passed to resolvers.

@typeParam — TContext - Context object type passed to resolvers.

@typeParam — TArgs - Argument object type passed to resolvers.

export interface GraphQLFieldConfig<TSource, TContext, TArgs = any> {

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

The GraphQL type reference or runtime type for this element.

type: GraphQLOutputType;

Arguments accepted by this field or directive.

args?: GraphQLFieldConfigArgumentMap;

Resolver function used to produce this field value.

resolve?: GraphQLFieldResolver<TSource, TContext, TArgs>;

Resolver function used to create a subscription event stream for this field.

subscribe?: GraphQLFieldResolver<TSource, TContext, TArgs>;

Reason this element is deprecated, if one was provided.

deprecationReason?: Maybe<string>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLFieldExtensions<TSource, TContext, TArgs>>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<FieldDefinitionNode>;
}
Referenced by

A map of argument names to argument configuration objects.

export type GraphQLFieldConfigArgumentMap = ObjMap<GraphQLArgumentConfig>
Referenced by

A map of field names to field configuration objects.

more
less

@typeParam — TSource - Source object type passed to resolvers.

@typeParam — TContext - Context object type passed to resolvers.

export type GraphQLFieldConfigMap<TSource, TContext> = ObjMap<GraphQLFieldConfig<TSource, TContext>>
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need. We've provided these template arguments because this is an open type and you may find them useful.

@typeParam — _TSource - Reserved source type parameter for extension typing.

@typeParam — _TContext - Reserved context type parameter for extension typing.

@typeParam — _TArgs - Reserved argument type parameter for extension typing.

export interface GraphQLFieldExtensions<_TSource, _TContext, _TArgs = any> {
[key: string]: unknown;
}
Referenced by

A map of field names to resolved field definitions.

more
less

@typeParam — TSource - Source object type passed to resolvers.

@typeParam — TContext - Context object type passed to resolvers.

export type GraphQLFieldMap<TSource, TContext> = ObjMap<GraphQLField<TSource, TContext>>
Referenced by

Resolves the runtime value for a GraphQL field.

more
less

@typeParam — TSource - Source object type passed to resolvers.

@typeParam — TContext - Context object type passed to resolvers.

@typeParam — TArgs - Argument object type passed to resolvers.

@typeParam — TResult - Result value type.

export type GraphQLFieldResolver<TSource, TContext, TArgs = any, TResult = unknown> = (source: TSource, args: TArgs, context: TContext, info: GraphQLResolveInfo) => TResult
Referenced by

A resolved GraphQL input field definition.

export interface GraphQLInputField {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description: Maybe<string>;

The GraphQL type reference or runtime type for this element.

type: GraphQLInputType;

Default value used when no explicit value is supplied.

defaultValue: unknown;

Reason this element is deprecated, if one was provided.

deprecationReason: Maybe<string>;

Custom extension fields reserved for users.

extensions: Readonly<GraphQLInputFieldExtensions>;

AST node from which this schema element was built, if available.

astNode: Maybe<InputValueDefinitionNode>;
}
Referenced by

Configuration used to define a GraphQL input field.

export interface GraphQLInputFieldConfig {

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

The GraphQL type reference or runtime type for this element.

type: GraphQLInputType;

Default value used when no explicit value is supplied.

defaultValue?: unknown;

Reason this element is deprecated, if one was provided.

deprecationReason?: Maybe<string>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLInputFieldExtensions>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<InputValueDefinitionNode>;
}
Referenced by

A map of input field names to input field configuration objects.

export type GraphQLInputFieldConfigMap = ObjMap<GraphQLInputFieldConfig>
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLInputFieldExtensions {
[key: string]: unknown;
}
Referenced by

A map of input field names to resolved input field definitions.

export type GraphQLInputFieldMap = ObjMap<GraphQLInputField>
Referenced by

Configuration used to construct a GraphQLInputObjectType.

export interface GraphQLInputObjectTypeConfig {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

Fields declared by this object, interface, input object, or literal.

fields: ThunkObjMap<GraphQLInputFieldConfig>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLInputObjectTypeExtensions>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<InputObjectTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes?: Maybe<readonly InputObjectTypeExtensionNode[]>;

Whether this input object uses the experimental OneOf input object semantics.

isOneOf?: boolean;
}
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLInputObjectTypeExtensions {
[key: string]: unknown;
}
Referenced by

Configuration used to construct a GraphQLInterfaceType.

more
less

@typeParam — TSource - Source object type passed to resolvers.

@typeParam — TContext - Context object type passed to resolvers.

export interface GraphQLInterfaceTypeConfig<TSource, TContext> {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

Interfaces implemented by this object or interface type.

interfaces?: ThunkReadonlyArray<GraphQLInterfaceType>;

Fields declared by this object, interface, input object, or literal.

fields: ThunkObjMap<GraphQLFieldConfig<TSource, TContext>>;

Optionally provide a custom type resolver function. If one is not provided, the default implementation will call isTypeOf on each implementing Object type.

resolveType?: Maybe<GraphQLTypeResolver<TSource, TContext>>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLInterfaceTypeExtensions>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<InterfaceTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes?: Maybe<readonly InterfaceTypeExtensionNode[]>;
}
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLInterfaceTypeExtensions {
[key: string]: unknown;
}
Referenced by

Checks whether a runtime value belongs to a GraphQL object type.

more
less

@typeParam — TSource - Source object type tested against this object type.

@typeParam — TContext - Context object type passed to resolvers.

export type GraphQLIsTypeOfFn<TSource, TContext> = (source: TSource, context: TContext, info: GraphQLResolveInfo) => PromiseOrValue<boolean>
Referenced by
Unexported symbols referenced here

@internal —

type PromiseOrValue<T> = Promise<T> | T
Referenced by

Configuration used to construct a GraphQLObjectType.

more
less

@typeParam — TSource - Source object type passed to resolvers.

@typeParam — TContext - Context object type passed to resolvers.

export interface GraphQLObjectTypeConfig<TSource, TContext> {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

Interfaces implemented by this object or interface type.

interfaces?: ThunkReadonlyArray<GraphQLInterfaceType>;

Fields declared by this object, interface, input object, or literal.

fields: ThunkObjMap<GraphQLFieldConfig<TSource, TContext>>;

Predicate used to determine whether a runtime value belongs to this object type.

isTypeOf?: Maybe<GraphQLIsTypeOfFn<TSource, TContext>>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLObjectTypeExtensions<TSource, TContext>>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<ObjectTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes?: Maybe<readonly ObjectTypeExtensionNode[]>;
}
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need. We've provided these template arguments because this is an open type and you may find them useful.

@typeParam — _TSource - Reserved source type parameter for extension typing.

@typeParam — _TContext - Reserved context type parameter for extension typing.

export interface GraphQLObjectTypeExtensions<_TSource = any, _TContext = any> {
[key: string]: unknown;
}
Referenced by

Information about the currently executing GraphQL field.

export interface GraphQLResolveInfo {

The field name referenced by this schema coordinate.

readonly fieldName: string;

AST field nodes that contributed to the current field execution.

readonly fieldNodes: readonly FieldNode[];

GraphQL output type declared for the current field.

readonly returnType: GraphQLOutputType;

Object type that owns the current field.

readonly parentType: GraphQLObjectType;

Response path where this error occurred during execution.

readonly path: Path;

The schema used for validation or execution.

readonly schema: GraphQLSchema;

Fragment definitions in the operation document keyed by fragment name.

readonly fragments: ObjMap<FragmentDefinitionNode>;

Initial root value passed to the operation.

readonly rootValue: unknown;

The operation selected for execution.

readonly operation: OperationDefinitionNode;

Runtime variable values keyed by variable name.

readonly variableValues: {
[key: string]: unknown;
};
}
Referenced by

Represents a linked response path from a field back to the root response.

export interface ResponsePath {

The previous segment in the linked response path, or undefined at the root.

readonly prev: Path | undefined;

The field name or list index for this response path segment.

readonly key: string | number;

The runtime object type name associated with this path segment, if known.

readonly typename: string | undefined;
}
Referenced by

Configuration used to construct a GraphQLScalarType.

more
less

@typeParam — TInternal - The internal runtime representation accepted by this scalar.

@typeParam — TExternal - The serialized representation exposed in GraphQL results.

export interface GraphQLScalarTypeConfig<TInternal, TExternal> {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

URL identifying the behavior specified for this custom scalar.

specifiedByURL?: Maybe<string>;

Serializes an internal value to include in a response.

serialize?: GraphQLScalarSerializer<TExternal>;

Parses an externally provided value to use as an input.

parseValue?: GraphQLScalarValueParser<TInternal>;

Parses an externally provided literal value to use as an input.

parseLiteral?: GraphQLScalarLiteralParser<TInternal>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLScalarTypeExtensions>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<ScalarTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes?: Maybe<readonly ScalarTypeExtensionNode[]>;
}
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLScalarTypeExtensions {
[key: string]: unknown;
}
Referenced by

Resolves the concrete object type for an abstract GraphQL type.

more
less

@typeParam — TSource - Source object type passed to resolvers.

@typeParam — TContext - Context object type passed to resolvers.

export type GraphQLTypeResolver<TSource, TContext> = (value: TSource, context: TContext, info: GraphQLResolveInfo, abstractType: GraphQLAbstractType) => PromiseOrValue<string | undefined>
Referenced by

Configuration used to construct a GraphQLUnionType.

more
less

@typeParam — TSource - Source object type passed to resolvers.

@typeParam — TContext - Context object type passed to resolvers.

export interface GraphQLUnionTypeConfig<TSource, TContext> {

The GraphQL name for this schema element.

name: string;

Human-readable description for this schema element, if provided.

description?: Maybe<string>;

Object types that belong to this union type.

types: ThunkReadonlyArray<GraphQLObjectType>;

Optionally provide a custom type resolver function. If one is not provided, the default implementation will call isTypeOf on each implementing Object type.

resolveType?: Maybe<GraphQLTypeResolver<TSource, TContext>>;

Custom extension fields reserved for users.

extensions?: Maybe<Readonly<GraphQLUnionTypeExtensions>>;

AST node from which this schema element was built, if available.

astNode?: Maybe<UnionTypeDefinitionNode>;

AST extension nodes applied to this schema element.

extensionASTNodes?: Maybe<readonly UnionTypeExtensionNode[]>;
}
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLUnionTypeExtensions {
[key: string]: unknown;
}
Referenced by

Serializes a runtime value as a scalar output value.

more
less

@typeParam — TExternal - The serialized representation returned for GraphQL results.

export type GraphQLScalarSerializer<TExternal> = (outputValue: unknown) => TExternal
Referenced by

Parses a runtime input value as a scalar input value.

more
less

@typeParam — TInternal - The internal runtime representation produced from variable input.

export type GraphQLScalarValueParser<TInternal> = (inputValue: unknown) => TInternal
Referenced by

Parses a GraphQL value literal as a scalar input value.

more
less

@typeParam — TInternal - The internal runtime representation produced from literal input.

export type GraphQLScalarLiteralParser<TInternal> = (valueNode: ValueNode, variables?: Maybe<ObjMap<unknown>>) => TInternal
Referenced by

Represents a range of characters represented by a lexical token within a Source.

export class Token {

Creates a Token instance.

more
less

@param — - Token kind produced by lexical analysis.

@param — - Character offset where this token begins.

@param — - Character offset where this token ends.

@param — - One-indexed line number where this token begins.

@param — - One-indexed column number where this token begins.

@param — - Interpreted value for non-punctuation tokens.

@example — ```ts import { Token, TokenKind } from 'graphql/language';

const token = new Token(TokenKind.NAME, 2, 7, 1, 3, 'hello');

token.kind; // => TokenKind.NAME token.value; // => 'hello' token.toJSON(); // => { kind: 'Name', value: 'hello', line: 1, column: 3 }

constructor(kind: TokenKind, start: number, end: number, line: number, column: number, value?: string)

The kind of Token.

readonly kind: TokenKind;

The character offset at which this Node begins.

readonly start: number;

The character offset at which this Node ends.

readonly end: number;

The 1-indexed line number on which this Token appears.

readonly line: number;

The 1-indexed column number at which this Token begins.

readonly column: number;

For non-punctuation tokens, represents the interpreted value of the token.

more
less

Note: is undefined for punctuation tokens, but typed as string for convenience in the parser.

readonly value: string;

Tokens exist as nodes in a double-linked-list amongst all tokens including ignored tokens. is always the first node and the last.

readonly prev: Token | null;

Next token in the token stream, including ignored tokens.

readonly next: Token | null;
get [Symbol.toStringTag](): string;

Returns a JSON representation of this token.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { Lexer, Source } from 'graphql/language';

const lexer = new Lexer(new Source('{ hello }')); const token = lexer.advance().toJSON();

token; // => { kind: '{', value: undefined, line: 1, column: 1 }

toJSON(): {
kind: TokenKind;
value?: string;
line: number;
column: number;
};
}
Referenced by

A representation of source input to GraphQL. The name and locationOffset parameters are optional, but they are useful for clients who store GraphQL documents in source files. For example, if the GraphQL input starts at line 40 in a file named Foo.graphql, it might be useful for name to be "Foo.graphql" and location to be { line: 40, column: 1 }. The line and column properties in locationOffset are 1-indexed.

export class Source {

Creates a Source instance.

more
less

@param — - The GraphQL source text.

@param — - Name used in diagnostics for this source.

@param — - One-indexed line and column where this source begins.

@example — ```ts import { Source } from 'graphql/language';

const source = new Source( 'type Query { greeting: String }', 'schema.graphql', { line: 10, column: 1 }, );

source.body; // => 'type Query { greeting: String }' source.name; // => 'schema.graphql' source.locationOffset; // => { line: 10, column: 1 }

constructor(body: string, name?: string, locationOffset?: Location)

The GraphQL source text.

body: string;

Name used in diagnostics for this source, such as a file path or request name.

name: string;

One-indexed line and column where this source begins.

locationOffset: Location;
get [Symbol.toStringTag](): string;
}
Referenced by
Unexported symbols referenced here

@category — Source

interface Location {
line: number;
column: number;
}
Referenced by

Contains a range of UTF-8 character offsets and token references that identify the region of the source from which the AST derived.

export class Location {

Creates a Location instance.

more
less

@param — - The start token.

@param — - The end token.

@param — - Source document used to derive error locations.

@example — ```ts import { Location, Source, Token, TokenKind } from 'graphql/language';

const source = new Source('{ hello }'); const startToken = new Token(TokenKind.BRACE_L, 0, 1, 1, 1); const endToken = new Token(TokenKind.BRACE_R, 8, 9, 1, 9); const location = new Location(startToken, endToken, source);

location.start; // => 0 location.end; // => 9 location.source.body; // => '{ hello }'

constructor(startToken: Token, endToken: Token, source: Source)

The character offset at which this Node begins.

readonly start: number;

The character offset at which this Node ends.

readonly end: number;

The Token at which this Node begins.

readonly startToken: Token;

The Token at which this Node ends.

readonly endToken: Token;

The Source document the AST represents.

readonly source: Source;
get [Symbol.toStringTag](): string;

Returns a JSON representation of this location.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { parse } from 'graphql/language';

const document = parse('{ hello }'); const location = document.loc?.toJSON();

location; // => { start: 0, end: 9 }

toJSON(): {
start: number;
end: number;
};
}
Referenced by

The operation types supported by GraphQL executable definitions.

more
less

@category — Kinds

export enum OperationTypeNode {

A query operation.

QUERY = "query",

A mutation operation.

MUTATION = "mutation",

A subscription operation.

SUBSCRIPTION = "subscription"
}
Referenced by

Takes a Source and a UTF-8 character offset, and returns the corresponding line and column as a SourceLocation.

more
less

@param — - The source document that contains the position.

@param — - The UTF-8 character offset in the source body.

@returns — The 1-indexed line and column for the given source position.

@example — ```ts import { Source, getLocation } from 'graphql/language';

const source = new Source('type Query { hello: String }'); const location = getLocation(source, 13);

location; // => { line: 1, column: 14 }

export function getLocation(source: Source, position: number): SourceLocation

Render a helpful description of the location in the GraphQL Source document.

more
less

@param — - The AST location to print.

@returns — A formatted source excerpt with line and column information.

@example — ```ts import { parse, printLocation } from 'graphql/language';

const document = parse('type Query { hello: String }'); const location = document.definitions[0].loc;

if (location) { const printed = printLocation(location);

printed; // => 'GraphQL request:1:1\n1 | type Query { hello: String }\n | ^' }

export function printLocation(location: Location): string

Render a helpful description of the location in the GraphQL Source document.

more
less

@param — - The source document that contains the location.

@param — - The 1-indexed line and column to print.

@returns — A formatted source excerpt with line and column information.

@example — ```ts import { Source, printSourceLocation } from 'graphql/language';

const source = new Source('type Query { hello: String }'); const printed = printSourceLocation(source, { line: 1, column: 14 });

printed; // => 'GraphQL request:1:14\n1 | type Query { hello: String }\n | ^'

export function printSourceLocation(source: Source, sourceLocation: SourceLocation): string

Given a Source object, creates a Lexer for that source. A Lexer is a stateful stream generator in that every time it is advanced, it returns the next token in the Source. Assuming the source lexes, the final Token emitted by the lexer will be of kind EOF, after which the lexer will repeatedly return the same EOF token whenever called.

export class Lexer implements LexerInterface {

Creates a Lexer instance.

more
less

@param — - Source document used to derive error locations.

@example — ```ts import { Lexer, Source, TokenKind } from 'graphql/language';

const lexer = new Lexer(new Source('{ hello }'));

lexer.token.kind; // => TokenKind.SOF lexer.advance().kind; // => TokenKind.BRACE_L lexer.advance().value; // => 'hello' lexer.advance().kind; // => TokenKind.BRACE_R

constructor(source: Source)

Source document used to derive error locations.

source: Source;

Most recent non-ignored token returned by the lexer.

lastToken: Token;

Current non-ignored token at the lexer cursor.

token: Token;

The (1-indexed) line containing the current token.

line: number;

Character offset where the current line starts.

lineStart: number;
get [Symbol.toStringTag](): string;

Advances the token stream to the next non-ignored token.

more
less

@returns — The next non-ignored token.

@example — ```ts import { Lexer, Source } from 'graphql/language';

const lexer = new Lexer(new Source('{ hello }')); const token = lexer.advance();

token.kind; // => '{' lexer.token; // => token

advance(): Token;

Looks ahead and returns the next non-ignored token, but does not change the state of Lexer.

more
less

@returns — The next non-ignored token without advancing the lexer.

@example — ```ts import { Lexer, Source } from 'graphql/language';

const lexer = new Lexer(new Source('{ hello }')); const token = lexer.lookahead();

token.kind; // => '{' lexer.token.kind; // => ''

lookahead(): Token;
}
Unexported symbols referenced here

A Lexer interface which provides common properties and methods required for lexing GraphQL source.

more
less

@internal —

interface LexerInterface {
source: Source;
lastToken: Token;
token: Token;
line: number;
lineStart: number;
advance: () => Token;
lookahead: () => Token;
}
Referenced by

@category — Lexing

more
less

An exported enum describing the different kinds of tokens that the lexer emits.

export enum TokenKind {

Start-of-file token.

SOF = "<SOF>",

End-of-file token.

EOF = "<EOF>",

The ! punctuation token.

BANG = "!",

The $ punctuation token.

DOLLAR = "$",

The & punctuation token.

AMP = "&",

The ( punctuation token.

PAREN_L = "(",

The ) punctuation token.

PAREN_R = ")",

The . punctuation token.

DOT = ".",

The ... spread punctuation token.

SPREAD = "...",

The : punctuation token.

COLON = ":",

The = punctuation token.

EQUALS = "=",

The @ punctuation token.

AT = "@",

The [ punctuation token.

BRACKET_L = "[",

The ] punctuation token.

BRACKET_R = "]",

The { punctuation token.

BRACE_L = "{",

The | punctuation token.

PIPE = "|",

The } punctuation token.

BRACE_R = "}",

A GraphQL name token or name AST node.

NAME = "Name",

An integer value token or AST node.

INT = "Int",

A floating-point value token or AST node.

FLOAT = "Float",

A string value token or AST node.

STRING = "String",

A block string value token.

BLOCK_STRING = "BlockString",

A comment token.

COMMENT = "Comment"
}
Referenced by

Given a GraphQL source, parses it into a Document. Throws GraphQLError if a syntax error is encountered.

more
less

@param — - A GraphQL source string or source object.

@param — - Optional parser configuration.

@returns — The parsed GraphQL document AST.

@example — ```ts // Parse a GraphQL document with the default parser options. import { parse } from 'graphql/language';

const document = parse('{ hero { name } }');

document.kind; // => 'Document'

@example — ```ts
// This variant enables parser options and provides an explicit lexer.
import { Lexer, Source, parse } from 'graphql/language';
const document = parse('fragment A($var: Boolean) on Query { field }', {
allowLegacyFragmentVariables: true,
maxTokens: 20,
noLocation: true,
});
const directiveDocument = parse('directive
@foo —
@bar — on FIELD', {
experimentalDirectivesOnDirectiveDefinitions: true,
});
const source = new Source('{ hero }');
const lexerDocument = parse(source, { lexer: new Lexer(source) });
document.definitions[0].kind; // => 'FragmentDefinition'
document.loc; // => undefined
directiveDocument.definitions[0].kind; // => 'DirectiveDefinition'
lexerDocument.definitions[0].kind; // => 'OperationDefinition'
export function parse(source: string | Source, options?: ParseOptions | undefined): DocumentNode

Given a string containing a GraphQL value (ex. [42]), parse the AST for that value. Throws GraphQLError if a syntax error is encountered.

more
less

This is useful within tools that operate upon GraphQL Values directly and in isolation of complete GraphQL documents.

Consider providing the results to the utility function: valueFromAST().

@param — - A GraphQL source string or source object containing a value.

@param — - Optional parser configuration.

@returns — The parsed GraphQL value AST.

@example — ```ts import { parseValue } from 'graphql/language';

const value = parseValue('[42]');

value.kind; // => 'ListValue'

export function parseValue(source: string | Source, options?: ParseOptions | undefined): ValueNode

Similar to parseValue(), but raises a parse error if it encounters a variable. The return type will be a constant value.

more
less

@param — - A GraphQL source string or source object containing a constant value.

@param — - Optional parser configuration.

@returns — The parsed GraphQL constant value AST.

@example — ```ts import { parseConstValue } from 'graphql/language';

const value = parseConstValue('{ enabled: true }');

value.kind; // => 'ObjectValue' parseConstValue('$variable'); // throws an error

export function parseConstValue(source: string | Source, options?: ParseOptions | undefined): ConstValueNode

Given a string containing a GraphQL Type (ex. [Int!]), parse the AST for that type. Throws GraphQLError if a syntax error is encountered.

more
less

This is useful within tools that operate upon GraphQL Types directly and in isolation of complete GraphQL documents.

Consider providing the results to the utility function: typeFromAST().

@param — - A GraphQL source string or source object containing a type reference.

@param — - Optional parser configuration.

@returns — The parsed GraphQL type AST.

@example — ```ts import { parseType } from 'graphql/language';

const type = parseType('[String!]');

type.kind; // => 'ListType'

export function parseType(source: string | Source, options?: ParseOptions | undefined): TypeNode

Given a string containing a GraphQL Schema Coordinate (ex. Type.field), parse the AST for that schema coordinate. Throws GraphQLError if a syntax error is encountered.

more
less

Consider providing the results to the utility function: resolveASTSchemaCoordinate(). Or calling resolveSchemaCoordinate() directly with an unparsed source.

@param — - A GraphQL source string or source object containing a schema coordinate.

@returns — The parsed GraphQL schema coordinate AST.

@example — ```ts import { parseSchemaCoordinate } from 'graphql/language';

const coordinate = parseSchemaCoordinate('Query.hero');

coordinate.kind; // => 'MemberCoordinate'

export function parseSchemaCoordinate(source: string | Source): SchemaCoordinateNode

Converts an AST into a string, using one set of reasonable formatting rules.

more
less

@param — - The GraphQL AST node to print.

@returns — A stable string representation of the AST.

@example — ```ts import { parse, print } from 'graphql';

const ast = parse('{ hero { name } }'); const text = print(ast);

text; // => '{\n hero {\n name\n }\n}'

export function print(ast: ASTNode): string

visit() will walk through an AST using a depth-first traversal, calling the visitor's enter function at each node in the traversal, and calling the leave function after visiting that node and all of its child nodes.

more
less

By returning different values from the enter and leave functions, the behavior of the visitor can be altered, including skipping over a sub-tree of the AST (by returning false), editing the AST by returning a value or null to remove the value, or to stop the whole traversal by returning BREAK.

When using visit() to edit an AST, the original AST will not be modified, and a new version of the AST with the changes applied will be returned from the visit function.

@param — - The AST node at which to start traversal.

@param — - The visitor or reducer functions to call while traversing.

@param — - Optional map of child keys to visit for each AST node kind.

@returns — The original AST, an edited AST, or a reduced value depending on the visitor.

@typeParam — N - The root AST node type returned when visiting without reducing.

@example — ```ts // Return values control traversal: undefined makes no change, false skips // a subtree, BREAK stops traversal, null removes a node, and any other // value replaces the current node. import { Kind, parse, print, visit } from 'graphql/language';

const document = parse('{ hero { name } }'); const editedAST = visit(document, { Field: (node) => { if (node.name.value === 'hero') { return { ...node, name: { kind: Kind.NAME, value: 'human' }, }; } }, });

print(editedAST); // => '{\n human {\n name\n }\n}'

@example — ```ts
// A named visitor function runs when entering nodes of that kind.
import { parse, visit } from 'graphql/language';
const document = parse('{ hero { name } }');
const fieldNames = [];
visit(document, {
Field: (node) => {
fieldNames.push(node.name.value);
},
});
fieldNames; // => ['hero', 'name']

@example — ```ts // A named visitor object can provide separate enter and leave handlers for // nodes of that kind. import { parse, visit } from 'graphql/language';

const document = parse('{ hero { name } }'); const events = [];

visit(document, { Field: { enter: (node) => { events.push(enter:${node.name.value}); }, leave: (node) => { events.push(leave:${node.name.value}); }, }, });

events; // => ['enter:hero', 'enter:name', 'leave:name', 'leave:hero']

@example — ```ts
// Generic enter and leave handlers run for every node.
import { parse, visit } from 'graphql/language';
const document = parse('{ hero { name } }');
let enterCount = 0;
let leaveCount = 0;
visit(document, {
enter: (node) => {
enterCount += 1;
},
leave: (node) => {
leaveCount += 1;
},
});
enterCount; // => leaveCount
enterCount > 0; // => true
export function visit<N extends ASTNode>(root: N, visitor: ASTVisitor, visitorKeys?: ASTVisitorKeyMap): N

Traverses an AST with reducer callbacks and returns the reduced value.

more
less

@param — - The AST node where traversal starts.

@param — - Reducer callbacks to invoke during traversal.

@param — - Optional mapping of child keys for each AST node kind.

@returns — The value produced by the reducer visitor.

@typeParam — R - The value produced by reducer visitor callbacks.

@example — ```ts // A reducer visitor returns values from leave handlers to build a reduced // result instead of returning an edited AST. import { parse, visit } from 'graphql/language';

const document = parse('{ hero { name } }'); const printed = visit(document, { Name: { leave: (node) => { return node.value; }, }, Field: { leave: (node) => { return node.selectionSet == null ? node.name : ${node.name} { ${node.selectionSet} }; }, }, SelectionSet: { leave: (node) => { return node.selections.join(' '); }, }, OperationDefinition: { leave: (node) => { return node.selectionSet; }, }, Document: { leave: (node) => { return node.definitions.join('\n'); }, }, });

printed; // => 'hero { name }'

export function visit<R>(root: ASTNode, visitor: ASTReducer<R>, visitorKeys?: ASTVisitorKeyMap): R
Unexported symbols referenced here

A reducer is composed of reducer functions that convert AST nodes into another form.

more
less

@internal —

type ASTReducer<R> = {
readonly [NodeT in ASTNode as NodeT["kind"]]?: {
readonly enter?: ASTVisitFn<NodeT>;
readonly leave: ASTReducerFn<NodeT, R>;
};
}
Referenced by
type ASTReducerFn<TReducedNode extends ASTNode, R> = (node: {
[K in keyof TReducedNode]: ReducedField<TReducedNode[K], R>;
}, key: string | number | undefined, parent: ASTNode | readonly ASTNode[] | undefined, path: readonly string | number[], ancestors: readonly ASTNode | readonly ASTNode[][]) => R
Referenced by
type ReducedField<T, R> = T extends null | undefined ? T : T extends readonly any[] ? readonly R[] : R
Referenced by

Creates a new visitor instance which delegates to many visitors to run in parallel. Each visitor will be visited for each node before moving on.

more
less

If a prior visitor edits a node, no following visitors will see that node.

@param — - The visitors to merge into one parallel visitor.

@returns — A visitor that delegates traversal to each provided visitor.

@example — ```ts import { parse, visit, visitInParallel } from 'graphql/language';

const document = parse('{ hero { name } }'); const events = [];

visit( document, visitInParallel([ { Field: (node) => { events.push(field:${node.name.value}); } }, { Name: (node) => { events.push(name:${node.value}); } }, ]), );

events; // => ['field:hero', 'name:hero', 'field:name', 'name:name']

export function visitInParallel(visitors: readonly ASTVisitor[]): ASTVisitor

Given a visitor instance, if it is leaving or not, and a node kind, return the function the visitor runtime should call. This deprecated compatibility helper delegates to getEnterLeaveForKind; call getEnterLeaveForKind directly because getVisitFn will be removed in v17.

more
less

@param — - The visitor object to inspect.

@param — - The AST node kind to resolve a handler for.

@param — - Whether to resolve the leave handler instead of the enter handler.

@returns — The visit function that applies for the given node kind and traversal phase, if one exists.

@example — ```ts import { Kind, getVisitFn } from 'graphql/language';

const enter = getVisitFn({ Field: () => {} }, Kind.FIELD, false); const leave = getVisitFn({ Field: () => {} }, Kind.FIELD, true);

typeof enter; // => 'function' leave; // => undefined

@category — Visiting
@deprecated — Please use `getEnterLeaveForKind` instead. Will be removed in v17
export function getVisitFn(visitor: ASTVisitor, kind: Kind, isLeaving: boolean): ASTVisitFn<ASTNode> | undefined

Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind.

more
less

@param — - The visitor object to inspect.

@param — - The AST node kind to resolve handlers for.

@returns — The enter and leave handlers that apply for the given node kind.

@example — ```ts import { Kind, getEnterLeaveForKind } from 'graphql/language';

const handlers = getEnterLeaveForKind({ Field: () => {} }, Kind.FIELD);

typeof handlers.enter; // => 'function' handlers.leave; // => undefined

export function getEnterLeaveForKind(visitor: ASTVisitor, kind: Kind): EnterLeaveVisitor<ASTNode>
Unexported symbols referenced here
interface EnterLeaveVisitor<TVisitedNode extends ASTNode> {
readonly enter?: ASTVisitFn<TVisitedNode>;
readonly leave?: ASTVisitFn<TVisitedNode>;
}
Referenced by

A value that can be returned from a visitor function to stop traversal.

export const BREAK: unknown = ...

@category — Kinds

more
less

The set of allowed kind values for AST nodes.

export enum Kind {

AST kind for name nodes.

NAME = "Name",

AST kind for document nodes.

DOCUMENT = "Document",

AST kind for operation definition nodes.

OPERATION_DEFINITION = "OperationDefinition",

AST kind for variable definition nodes.

VARIABLE_DEFINITION = "VariableDefinition",

AST kind for selection set nodes.

SELECTION_SET = "SelectionSet",

AST kind for field selection nodes.

FIELD = "Field",

AST kind for argument nodes.

ARGUMENT = "Argument",

AST kind for fragment spread nodes.

FRAGMENT_SPREAD = "FragmentSpread",

AST kind for inline fragment nodes.

INLINE_FRAGMENT = "InlineFragment",

AST kind for fragment definition nodes.

FRAGMENT_DEFINITION = "FragmentDefinition",

AST kind for variable reference nodes.

VARIABLE = "Variable",

AST kind for integer value nodes.

INT = "IntValue",

AST kind for floating-point value nodes.

FLOAT = "FloatValue",

AST kind for string value nodes.

STRING = "StringValue",

AST kind for boolean value nodes.

BOOLEAN = "BooleanValue",

AST kind for null value nodes.

NULL = "NullValue",

AST kind for enum value nodes.

ENUM = "EnumValue",

AST kind for list value nodes.

LIST = "ListValue",

AST kind for object value nodes.

OBJECT = "ObjectValue",

AST kind for object field nodes.

OBJECT_FIELD = "ObjectField",

AST kind for directive nodes.

DIRECTIVE = "Directive",

AST kind for named type reference nodes.

NAMED_TYPE = "NamedType",

AST kind for list type reference nodes.

LIST_TYPE = "ListType",

AST kind for non-null type reference nodes.

NON_NULL_TYPE = "NonNullType",

AST kind for schema definition nodes.

SCHEMA_DEFINITION = "SchemaDefinition",

AST kind for operation type definition nodes.

OPERATION_TYPE_DEFINITION = "OperationTypeDefinition",

AST kind for scalar type definition nodes.

SCALAR_TYPE_DEFINITION = "ScalarTypeDefinition",

AST kind for object type definition nodes.

OBJECT_TYPE_DEFINITION = "ObjectTypeDefinition",

AST kind for field definition nodes.

FIELD_DEFINITION = "FieldDefinition",

AST kind for input value definition nodes.

INPUT_VALUE_DEFINITION = "InputValueDefinition",

AST kind for interface type definition nodes.

INTERFACE_TYPE_DEFINITION = "InterfaceTypeDefinition",

AST kind for union type definition nodes.

UNION_TYPE_DEFINITION = "UnionTypeDefinition",

AST kind for enum type definition nodes.

ENUM_TYPE_DEFINITION = "EnumTypeDefinition",

AST kind for enum value definition nodes.

ENUM_VALUE_DEFINITION = "EnumValueDefinition",

AST kind for input object type definition nodes.

INPUT_OBJECT_TYPE_DEFINITION = "InputObjectTypeDefinition",

AST kind for directive definition nodes.

DIRECTIVE_DEFINITION = "DirectiveDefinition",

AST kind for schema extension nodes.

SCHEMA_EXTENSION = "SchemaExtension",

AST kind for directive extension nodes.

DIRECTIVE_EXTENSION = "DirectiveExtension",

AST kind for scalar type extension nodes.

SCALAR_TYPE_EXTENSION = "ScalarTypeExtension",

AST kind for object type extension nodes.

OBJECT_TYPE_EXTENSION = "ObjectTypeExtension",

AST kind for interface type extension nodes.

INTERFACE_TYPE_EXTENSION = "InterfaceTypeExtension",

AST kind for union type extension nodes.

UNION_TYPE_EXTENSION = "UnionTypeExtension",

AST kind for enum type extension nodes.

ENUM_TYPE_EXTENSION = "EnumTypeExtension",

AST kind for input object type extension nodes.

INPUT_OBJECT_TYPE_EXTENSION = "InputObjectTypeExtension",

AST kind for type coordinate nodes.

TYPE_COORDINATE = "TypeCoordinate",

AST kind for member coordinate nodes.

MEMBER_COORDINATE = "MemberCoordinate",

AST kind for argument coordinate nodes.

ARGUMENT_COORDINATE = "ArgumentCoordinate",

AST kind for directive coordinate nodes.

DIRECTIVE_COORDINATE = "DirectiveCoordinate",

AST kind for directive argument coordinate nodes.

DIRECTIVE_ARGUMENT_COORDINATE = "DirectiveArgumentCoordinate"
}
Referenced by

@category — Kinds

more
less

The set of allowed directive location values.

export enum DirectiveLocation {

Directive location for query operations.

QUERY = "QUERY",

Directive location for mutation operations.

MUTATION = "MUTATION",

Directive location for subscription operations.

SUBSCRIPTION = "SUBSCRIPTION",

Directive location for field selections.

FIELD = "FIELD",

Directive location for fragment definitions.

FRAGMENT_DEFINITION = "FRAGMENT_DEFINITION",

Directive location for fragment spreads.

FRAGMENT_SPREAD = "FRAGMENT_SPREAD",

Directive location for inline fragments.

INLINE_FRAGMENT = "INLINE_FRAGMENT",

Directive location for variable definitions.

VARIABLE_DEFINITION = "VARIABLE_DEFINITION",

Directive location for schema definitions and extensions.

SCHEMA = "SCHEMA",

Directive location for scalar type definitions and extensions.

SCALAR = "SCALAR",

Directive location for object type definitions and extensions.

OBJECT = "OBJECT",

Directive location for field definitions.

FIELD_DEFINITION = "FIELD_DEFINITION",

Directive location for argument definitions.

ARGUMENT_DEFINITION = "ARGUMENT_DEFINITION",

Directive location for interface type definitions and extensions.

INTERFACE = "INTERFACE",

Directive location for union type definitions and extensions.

UNION = "UNION",

Directive location for enum type definitions and extensions.

ENUM = "ENUM",

Directive location for enum value definitions.

ENUM_VALUE = "ENUM_VALUE",

Directive location for input object type definitions and extensions.

INPUT_OBJECT = "INPUT_OBJECT",

Directive location for input object field definitions.

INPUT_FIELD_DEFINITION = "INPUT_FIELD_DEFINITION",

Directive location for directive definitions and extensions.

DIRECTIVE_DEFINITION = "DIRECTIVE_DEFINITION"
}
Referenced by

Returns true when the AST node is a definition node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is a definition node.

@example — ```ts import { parse, isDefinitionNode } from 'graphql/language';

const document = parse('{ hello }');

isDefinitionNode(document.definitions[0]); // => true isDefinitionNode(document); // => false

export function isDefinitionNode(node: ASTNode): node is DefinitionNode

Returns true when the AST node is an executable definition node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is an executable definition node.

@example — ```ts import { parse, isExecutableDefinitionNode } from 'graphql/language';

const query = parse('{ hello }'); const schema = parse('type Query { hello: String }');

isExecutableDefinitionNode(query.definitions[0]); // => true isExecutableDefinitionNode(schema.definitions[0]); // => false

export function isExecutableDefinitionNode(node: ASTNode): node is ExecutableDefinitionNode

Returns true when the AST node is a selection node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is a selection node.

@example — ```ts import { Kind, isSelectionNode } from 'graphql/language';

const field = { kind: Kind.FIELD, name: { kind: Kind.NAME, value: 'hello' } }; const document = { kind: Kind.DOCUMENT, definitions: [] };

isSelectionNode(field); // => true isSelectionNode(document); // => false

export function isSelectionNode(node: ASTNode): node is SelectionNode

Returns true when the AST node is a value node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is a value node.

@example — ```ts import { parseType, parseValue, isValueNode } from 'graphql/language';

const value = parseValue('[42]'); const type = parseType('[String!]');

isValueNode(value); // => true isValueNode(type); // => false

export function isValueNode(node: ASTNode): node is ValueNode

Returns true when the AST node is a constant value node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is a constant value node.

@example — ```ts import { parseConstValue, parseValue, isConstValueNode } from 'graphql/language';

const value = parseConstValue('[42]'); const variable = parseValue('$id');

isConstValueNode(value); // => true isConstValueNode(variable); // => false

export function isConstValueNode(node: ASTNode): node is ConstValueNode

Returns true when the AST node is a type node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is a type node.

@example — ```ts import { parseType, parseValue, isTypeNode } from 'graphql/language';

const type = parseType('[String!]'); const value = parseValue('[42]');

isTypeNode(type); // => true isTypeNode(value); // => false

export function isTypeNode(node: ASTNode): node is TypeNode

Returns true when the AST node is a type system definition node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is a type system definition node.

@example — ```ts import { parse, isTypeSystemDefinitionNode } from 'graphql/language';

const schema = parse('type Query { hello: String }'); const query = parse('{ hello }');

isTypeSystemDefinitionNode(schema.definitions[0]); // => true isTypeSystemDefinitionNode(query.definitions[0]); // => false

export function isTypeSystemDefinitionNode(node: ASTNode): node is TypeSystemDefinitionNode

Returns true when the AST node is a type definition node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is a type definition node.

@example — ```ts import { parse, isTypeDefinitionNode } from 'graphql/language';

const typeDefinition = parse('type Query { hello: String }'); const directiveDefinition = parse('directive

@cache — on FIELD');

isTypeDefinitionNode(typeDefinition.definitions[0]); // => true isTypeDefinitionNode(directiveDefinition.definitions[0]); // => false

export function isTypeDefinitionNode(node: ASTNode): node is TypeDefinitionNode

Returns true when the AST node is a type system extension node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is a type system extension node.

@example — ```ts import { parse, isTypeSystemExtensionNode } from 'graphql/language';

const extension = parse('extend type Query { hello: String }'); const definition = parse('type Query { hello: String }');

isTypeSystemExtensionNode(extension.definitions[0]); // => true isTypeSystemExtensionNode(definition.definitions[0]); // => false

export function isTypeSystemExtensionNode(node: ASTNode): node is TypeSystemExtensionNode

Returns true when the AST node is a type extension node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is a type extension node.

@example — ```ts import { parse, isTypeExtensionNode } from 'graphql/language';

const extension = parse('extend type Query { hello: String }'); const schemaExtension = parse('extend schema { query: Query }');

isTypeExtensionNode(extension.definitions[0]); // => true isTypeExtensionNode(schemaExtension.definitions[0]); // => false

export function isTypeExtensionNode(node: ASTNode): node is TypeExtensionNode

Returns true when the AST node is a schema coordinate node.

more
less

@param — - The AST node to test.

@returns — True when the AST node is a schema coordinate node.

@example — ```ts import { parse, parseSchemaCoordinate, isSchemaCoordinateNode, } from 'graphql/language';

const coordinate = parseSchemaCoordinate('Query.hero'); const document = parse('{ hero }');

isSchemaCoordinateNode(coordinate); // => true isSchemaCoordinateNode(document); // => false

export function isSchemaCoordinateNode(node: ASTNode): node is SchemaCoordinateNode

Configuration options to control parser behavior

export interface ParseOptions {

By default, the parser creates AST nodes that know the location in the source that they correspond to. This configuration flag disables that behavior for performance or testing.

noLocation?: boolean;

Parser CPU and memory usage is linear to the number of tokens in a document however in extreme cases it becomes quadratic due to memory exhaustion. Parsing happens before validation so even invalid queries can burn lots of CPU time and memory. To prevent this you can set a maximum number of tokens allowed within a document.

maxTokens?: number | undefined;

Deprecated option that allows legacy fragment variable definitions to be parsed. This legacy fragment variable syntax will be removed in v17. Move variable definitions to operations for spec-compliant documents; if you need variables or arguments scoped to fragments, v17 has a more complete experimental fragment-arguments feature.

more
less

@example — The syntax is identical to normal, query-defined variables.

fragment A($var: Boolean = false) on T {
  ...
}

@deprecated — will be removed in the v17.0.0

If enabled, the parser will understand and parse variable definitions contained in a fragment definition. They'll be represented in the variableDefinitions field of the FragmentDefinitionNode.

allowLegacyFragmentVariables?: boolean;

EXPERIMENTAL:

more
less

If enabled, the parser will parse directives on directive definitions. This syntax is not part of the GraphQL specification and may change.

@example — ```graphql directive

@foo —

@bar — on FIELD

experimentalDirectivesOnDirectiveDefinitions?: boolean;

Internal parser hook for GraphQL.js entry points that need to parse a restricted grammar with an alternate lexer.

more
less

@internal —

lexer?: LexerInterface | undefined;
}
Referenced by

Represents a location in a Source.

export interface SourceLocation {

One-indexed line number in the source document.

readonly line: number;

One-indexed column number in the source document.

readonly column: number;
}
Referenced by

Deprecated legacy alias for the enum type representing token kind values. This alias will be removed in v17. In v17, TokenKind is exported as the single public symbol for both the runtime object and the corresponding TypeScript type.

more
less

@deprecated — Will be removed in v17. In v17, use TokenKind as both the runtime value and the type.

export type TokenKindEnum = typeof TokenKind

Deprecated legacy alias for the enum type representing the possible kind values of AST nodes. This alias will be removed in v17. In v17, Kind is exported as the single public symbol for both the runtime object and the corresponding TypeScript type.

more
less

@deprecated — Will be removed in v17. In v17, use Kind as both the runtime value and the type.

export type KindEnum = typeof Kind

Deprecated legacy alias for the enum type representing directive location values. This alias will be removed in v17. In v17, DirectiveLocation is exported as the single public symbol for both the runtime object and the corresponding TypeScript type.

more
less

@deprecated — Will be removed in v17. In v17, use DirectiveLocation as both the runtime value and the type.

export type DirectiveLocationEnum = typeof DirectiveLocation

A visitor defines the callbacks called during AST traversal.

export type ASTVisitor = EnterLeaveVisitor<ASTNode> | KindVisitor
Referenced by
Unexported symbols referenced here
type KindVisitor = {
readonly [NodeT in ASTNode as NodeT["kind"]]?: ASTVisitFn<NodeT> | EnterLeaveVisitor<NodeT>;
}
Referenced by

A visitor is composed of visit functions called for each node during traversal.

more
less

@typeParam — TVisitedNode - AST node type handled by this visitor function.

export type ASTVisitFn<TVisitedNode extends ASTNode> = (node: TVisitedNode, key: string | number | undefined, parent: ASTNode | readonly ASTNode[] | undefined, path: readonly string | number[], ancestors: readonly ASTNode | readonly ASTNode[][]) => any
Referenced by

Deprecated visitor key map type retained for compatibility. Inline this mapped type at use sites because ASTVisitorKeyMap will be removed in v17.

more
less

@deprecated — Please inline it. Will be removed in v17

export type ASTVisitorKeyMap = {
[NodeT in ASTNode as NodeT["kind"]]?: readonly keyof NodeT[];
}
Referenced by
Referenced by

Utility type listing all nodes indexed by their kind.

export type ASTKindToNode = {
[NodeT in ASTNode as NodeT["kind"]]: NodeT;
}

An identifier in a GraphQL document.

export interface NameNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: NAME;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Parsed value represented by this node.

readonly value: string;
}
Referenced by

The root AST node for a parsed GraphQL document.

export interface DocumentNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: DOCUMENT;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Top-level executable and type-system definitions in this document.

readonly definitions: readonly DefinitionNode[];

The number of lexical tokens parsed for this document, if token counting was enabled.

readonly tokenCount?: number | undefined;
}
Referenced by

Any top-level definition that may appear in a GraphQL document.

export type DefinitionNode = ExecutableDefinitionNode | TypeSystemDefinitionNode | TypeSystemExtensionNode
Referenced by

Any executable definition that may appear in an operation document.

export type ExecutableDefinitionNode = OperationDefinitionNode | FragmentDefinitionNode
Referenced by

A query, mutation, or subscription operation definition.

export interface OperationDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: OPERATION_DEFINITION;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The operation selected for execution.

readonly operation: OperationTypeNode;

Name node identifying this AST node.

readonly name?: NameNode;

Variable definitions declared by this operation or fragment.

readonly variableDefinitions?: readonly VariableDefinitionNode[];

Directives available in this schema or applied to this AST node.

readonly directives?: readonly DirectiveNode[];

Selections made by this operation, field, or fragment.

readonly selectionSet: SelectionSetNode;
}
Referenced by

A variable declaration in an operation or legacy fragment definition.

export interface VariableDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: VARIABLE_DEFINITION;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The variable being defined or referenced.

readonly variable: VariableNode;

The GraphQL type reference or runtime type for this element.

readonly type: TypeNode;

Default value used when no explicit value is supplied.

readonly defaultValue?: ConstValueNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];
}
Referenced by

A variable reference, such as $id.

export interface VariableNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: VARIABLE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;
}
Referenced by

A set of fields and fragments selected from an object, interface, or union.

export interface SelectionSetNode {

The discriminator identifying the concrete AST or introspection kind.

kind: SELECTION_SET;

The source location for this AST node, if location tracking was enabled.

loc?: Location;

Fields and fragments contained in this selection set.

selections: readonly SelectionNode[];
}
Referenced by

Any selection that may appear inside a selection set.

export type SelectionNode = FieldNode | FragmentSpreadNode | InlineFragmentNode
Referenced by

A field selected in an executable GraphQL document.

export interface FieldNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: FIELD;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The response-key alias for this field, if one was supplied.

readonly alias?: NameNode;

Name node identifying this AST node.

readonly name: NameNode;

Arguments supplied to this field, directive, or coordinate.

readonly arguments?: readonly ArgumentNode[];

Directives available in this schema or applied to this AST node.

readonly directives?: readonly DirectiveNode[];

Selections made by this operation, field, or fragment.

readonly selectionSet?: SelectionSetNode;
}
Referenced by

An argument supplied to a field or directive.

export interface ArgumentNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: ARGUMENT;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Parsed value represented by this node.

readonly value: ValueNode;
}
Referenced by

An argument node whose value is guaranteed to be constant.

export interface ConstArgumentNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: ARGUMENT;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Parsed value represented by this node.

readonly value: ConstValueNode;
}
Referenced by

A named fragment spread, such as ...userFields.

export interface FragmentSpreadNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: FRAGMENT_SPREAD;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly DirectiveNode[];
}
Referenced by

An inline fragment spread with an optional type condition.

export interface InlineFragmentNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: INLINE_FRAGMENT;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The type condition that limits where this fragment applies.

readonly typeCondition?: NamedTypeNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly DirectiveNode[];

Selections made by this operation, field, or fragment.

readonly selectionSet: SelectionSetNode;
}
Referenced by

A reusable fragment definition declared in an executable document.

export interface FragmentDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: FRAGMENT_DEFINITION;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Deprecated variable definitions declared by this legacy fragment definition. This legacy fragment variable syntax will be removed in v17. Move variable definitions to operations for spec-compliant documents; if you need variables or arguments scoped to fragments, v17 has a more complete experimental fragment-arguments feature.

more
less

@deprecated — variableDefinitions will be removed in v17.0.0

readonly variableDefinitions?: readonly VariableDefinitionNode[];

The type condition that limits where this fragment applies.

readonly typeCondition: NamedTypeNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly DirectiveNode[];

Selections made by this operation, field, or fragment.

readonly selectionSet: SelectionSetNode;
}
Referenced by

An integer value literal.

export interface IntValueNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: INT;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Parsed value represented by this node.

readonly value: string;
}
Referenced by

A floating-point value literal.

export interface FloatValueNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: FLOAT;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Parsed value represented by this node.

readonly value: string;
}
Referenced by

A string value literal.

export interface StringValueNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: STRING;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Parsed value represented by this node.

readonly value: string;

Whether this string was parsed from block string syntax.

readonly block?: boolean;
}
Referenced by

A boolean value literal.

export interface BooleanValueNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: BOOLEAN;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Parsed value represented by this node.

readonly value: boolean;
}
Referenced by

A null value literal.

export interface NullValueNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: NULL;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;
}
Referenced by

An enum value literal.

export interface EnumValueNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: ENUM;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Parsed value represented by this node.

readonly value: string;
}
Referenced by

A list value literal.

export interface ListValueNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: LIST;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Values contained in this enum, list, or input-object definition.

readonly values: readonly ValueNode[];
}
Referenced by

A list value literal whose elements are all constant values.

export interface ConstListValueNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: LIST;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Values contained in this enum, list, or input-object definition.

readonly values: readonly ConstValueNode[];
}
Referenced by

An input object value literal.

export interface ObjectValueNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: OBJECT;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Fields declared by this object, interface, input object, or literal.

readonly fields: readonly ObjectFieldNode[];
}
Referenced by

An input object value literal whose fields are all constant values.

export interface ConstObjectValueNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: OBJECT;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Fields declared by this object, interface, input object, or literal.

readonly fields: readonly ConstObjectFieldNode[];
}
Referenced by

A field inside an input object value literal.

export interface ObjectFieldNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: OBJECT_FIELD;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Parsed value represented by this node.

readonly value: ValueNode;
}
Referenced by

A field inside a constant input object value literal.

export interface ConstObjectFieldNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: OBJECT_FIELD;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Parsed value represented by this node.

readonly value: ConstValueNode;
}
Referenced by

A directive applied to an executable or type-system location.

export interface DirectiveNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: DIRECTIVE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Arguments supplied to this field, directive, or coordinate.

readonly arguments?: readonly ArgumentNode[];
}
Referenced by

A directive whose arguments are all constant values.

export interface ConstDirectiveNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: DIRECTIVE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Arguments supplied to this field, directive, or coordinate.

readonly arguments?: readonly ConstArgumentNode[];
}
Referenced by

A named type reference.

export interface NamedTypeNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: NAMED_TYPE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;
}
Referenced by

A list type reference.

export interface ListTypeNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: LIST_TYPE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The GraphQL type reference or runtime type for this element.

readonly type: TypeNode;
}
Referenced by

A non-null type reference.

export interface NonNullTypeNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: NON_NULL_TYPE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The GraphQL type reference or runtime type for this element.

readonly type: NamedTypeNode | ListTypeNode;
}
Referenced by

Any type-system definition that may appear in a schema document.

export type TypeSystemDefinitionNode = SchemaDefinitionNode | TypeDefinitionNode | DirectiveDefinitionNode
Referenced by

A schema definition in a type-system document.

export interface SchemaDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: SCHEMA_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Root operation types declared by this schema definition or extension.

readonly operationTypes: readonly OperationTypeDefinitionNode[];
}
Referenced by

A root operation type declaration inside a schema definition or extension.

export interface OperationTypeDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: OPERATION_TYPE_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The operation selected for execution.

readonly operation: OperationTypeNode;

The GraphQL type reference or runtime type for this element.

readonly type: NamedTypeNode;
}
Referenced by

A scalar type definition in a type-system document.

export interface ScalarTypeDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: SCALAR_TYPE_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];
}
Referenced by

An object type definition in a type-system document.

export interface ObjectTypeDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: OBJECT_TYPE_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Name node identifying this AST node.

readonly name: NameNode;

Interfaces implemented by this object or interface type.

readonly interfaces?: readonly NamedTypeNode[];

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Fields declared by this object, interface, input object, or literal.

readonly fields?: readonly FieldDefinitionNode[];
}
Referenced by

A field definition declared by an object or interface type.

export interface FieldDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: FIELD_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Name node identifying this AST node.

readonly name: NameNode;

Arguments supplied to this field, directive, or coordinate.

readonly arguments?: readonly InputValueDefinitionNode[];

The GraphQL type reference or runtime type for this element.

readonly type: TypeNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];
}
Referenced by

An argument or input-field definition.

export interface InputValueDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: INPUT_VALUE_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Name node identifying this AST node.

readonly name: NameNode;

The GraphQL type reference or runtime type for this element.

readonly type: TypeNode;

Default value used when no explicit value is supplied.

readonly defaultValue?: ConstValueNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];
}
Referenced by

An interface type definition in a type-system document.

export interface InterfaceTypeDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: INTERFACE_TYPE_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Name node identifying this AST node.

readonly name: NameNode;

Interfaces implemented by this object or interface type.

readonly interfaces?: readonly NamedTypeNode[];

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Fields declared by this object, interface, input object, or literal.

readonly fields?: readonly FieldDefinitionNode[];
}
Referenced by

A union type definition in a type-system document.

export interface UnionTypeDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: UNION_TYPE_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Object types that belong to this union type.

readonly types?: readonly NamedTypeNode[];
}
Referenced by

An enum type definition in a type-system document.

export interface EnumTypeDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: ENUM_TYPE_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Values contained in this enum, list, or input-object definition.

readonly values?: readonly EnumValueDefinitionNode[];
}
Referenced by

An enum value definition.

export interface EnumValueDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: ENUM_VALUE_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];
}
Referenced by

An input object type definition in a type-system document.

export interface InputObjectTypeDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: INPUT_OBJECT_TYPE_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Fields declared by this object, interface, input object, or literal.

readonly fields?: readonly InputValueDefinitionNode[];
}
Referenced by

A directive definition in a type-system document.

export interface DirectiveDefinitionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: DIRECTIVE_DEFINITION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

The optional GraphQL description associated with this definition.

readonly description?: StringValueNode;

Name node identifying this AST node.

readonly name: NameNode;

Arguments supplied to this field, directive, or coordinate.

readonly arguments?: readonly InputValueDefinitionNode[];

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Whether this directive may appear more than once at the same location.

readonly repeatable: boolean;

Locations where this directive may be applied.

readonly locations: readonly NameNode[];
}
Referenced by

Any type-system extension that may appear in a schema extension document.

export type TypeSystemExtensionNode = SchemaExtensionNode | TypeExtensionNode | DirectiveExtensionNode
Referenced by

A schema extension in a type-system document.

export interface SchemaExtensionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: SCHEMA_EXTENSION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Root operation types declared by this schema definition or extension.

readonly operationTypes?: readonly OperationTypeDefinitionNode[];
}
Referenced by

A scalar type extension.

export interface ScalarTypeExtensionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: SCALAR_TYPE_EXTENSION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];
}
Referenced by

An object type extension.

export interface ObjectTypeExtensionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: OBJECT_TYPE_EXTENSION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Interfaces implemented by this object or interface type.

readonly interfaces?: readonly NamedTypeNode[];

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Fields declared by this object, interface, input object, or literal.

readonly fields?: readonly FieldDefinitionNode[];
}
Referenced by

An interface type extension.

export interface InterfaceTypeExtensionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: INTERFACE_TYPE_EXTENSION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Interfaces implemented by this object or interface type.

readonly interfaces?: readonly NamedTypeNode[];

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Fields declared by this object, interface, input object, or literal.

readonly fields?: readonly FieldDefinitionNode[];
}
Referenced by

A union type extension.

export interface UnionTypeExtensionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: UNION_TYPE_EXTENSION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Object types that belong to this union type.

readonly types?: readonly NamedTypeNode[];
}
Referenced by

An enum type extension.

export interface EnumTypeExtensionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: ENUM_TYPE_EXTENSION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Values contained in this enum, list, or input-object definition.

readonly values?: readonly EnumValueDefinitionNode[];
}
Referenced by

An input object type extension.

export interface InputObjectTypeExtensionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: INPUT_OBJECT_TYPE_EXTENSION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];

Fields declared by this object, interface, input object, or literal.

readonly fields?: readonly InputValueDefinitionNode[];
}
Referenced by

A directive extension.

export interface DirectiveExtensionNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: DIRECTIVE_EXTENSION;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

Directives available in this schema or applied to this AST node.

readonly directives?: readonly ConstDirectiveNode[];
}
Referenced by

A schema coordinate that refers to a named type.

export interface TypeCoordinateNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: TYPE_COORDINATE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;
}
Referenced by

A schema coordinate that refers to a member of a named type.

export interface MemberCoordinateNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: MEMBER_COORDINATE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

The member name referenced by this schema coordinate.

readonly memberName: NameNode;
}
Referenced by

A schema coordinate that refers to a field or directive argument.

export interface ArgumentCoordinateNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: ARGUMENT_COORDINATE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

The field name referenced by this schema coordinate.

readonly fieldName: NameNode;

The argument name referenced by this schema coordinate.

readonly argumentName: NameNode;
}
Referenced by

A schema coordinate that refers to a directive.

export interface DirectiveCoordinateNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: DIRECTIVE_COORDINATE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;
}
Referenced by

A schema coordinate that refers to a directive argument.

export interface DirectiveArgumentCoordinateNode {

The discriminator identifying the concrete AST or introspection kind.

readonly kind: DIRECTIVE_ARGUMENT_COORDINATE;

The source location for this AST node, if location tracking was enabled.

readonly loc?: Location;

Name node identifying this AST node.

readonly name: NameNode;

The argument name referenced by this schema coordinate.

readonly argumentName: NameNode;
}
Referenced by

Implements the "Executing requests" section of the GraphQL specification.

more
less

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.

@param — - The arguments used to perform the operation.

@returns — A completed execution result, or a promise resolving to one when execution is asynchronous.

@example — ```ts // Execute an asynchronous operation with variables. 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!' } }

@example — ```ts
// This variant supplies context plus custom field and type resolvers.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { execute } from 'graphql/execution';
const schema = buildSchema(`
interface Named {
name: String!
}
type User implements Named {
name: String!
}
type Query {
viewer: Named
}
`);
const result = await execute({
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;
},
});
result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } }

@example — ```ts // This variant shows how resolver errors become field errors in the result. import { parse } from 'graphql/language'; import { buildSchema } from 'graphql/utilities'; import { execute } from 'graphql/execution';

const schema = buildSchema( type Query { broken: String }); const document = parse('{ broken }');

const result = await execute({ schema, document, rootValue: { broken: () => { throw new Error('Resolver failed.'); }, }, });

result.data.broken; // => null result.errors[0].message; // => 'Resolver failed.'

@example — ```ts
// This variant limits how many variable coercion errors are reported.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { execute } 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 result = await execute({
schema,
document,
variableValues: {
first: { stars: 'bad' },
second: { stars: 'also bad' },
},
options: { maxCoercionErrors: 1 },
});
result.errors.length; // => 2
result.errors[1].message; // matches /error limit reached/
export function execute(args: ExecutionArgs): PromiseOrValue<ExecutionResult>

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.

more
less

@param — - The arguments used to perform the operation.

@returns — Completed execution output for a synchronous operation.

@example — ```ts // Execute an operation synchronously when all resolvers are synchronous. import { parse } from 'graphql/language'; import { buildSchema } from 'graphql/utilities'; import { executeSync } from 'graphql/execution';

const schema = buildSchema( type Query { greeting: String }); const document = parse('{ greeting }');

const result = executeSync({ schema, document, rootValue: { greeting: 'Hello', }, });

result; // => { data: { greeting: 'Hello' } }

@example — ```ts
// This variant shows executeSync throwing when a resolver returns a promise.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { executeSync } from 'graphql/execution';
const schema = buildSchema(`
type Query {
greeting: String
}
`);
executeSync({
schema,
document: parse('{ greeting }'),
rootValue: {
greeting: async () => 'Hello',
},
}); // throws an error
export function executeSync(args: ExecutionArgs): ExecutionResult

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.

export const defaultFieldResolver: GraphQLFieldResolver<unknown, unknown> = ...

If a resolveType function is not given, then a default resolve behavior is used which attempts two strategies:

more
less

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.

export const defaultTypeResolver: GraphQLTypeResolver<unknown, unknown> = ...

Given a Path, return an Array of the path keys.

more
less

@param — - The linked response path to flatten.

@returns — An array of response path keys from root to leaf.

@example — ```ts 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); // => []

export function responsePathAsArray(path: Maybe<Readonly<Path>>): string | number[]

Prepares an object map of argument values given a list of argument definitions and list of argument AST nodes.

more
less

Note: Returned value is a plain Object with a prototype, since it is exposed to user code. Care should be taken to not pull values from the Object prototype.

@param — - The field or directive definition whose arguments should be coerced.

@param — - The AST node to inspect.

@param — - The runtime variable values keyed by variable name.

@returns — Coerced argument values keyed by argument name.

@example — ```ts // 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 }

@example — ```ts
// This variant resolves argument values from operation variables.
import { parse } from 'graphql/language';
import { buildSchema } from 'graphql/utilities';
import { getArgumentValues } 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 fieldNode = document.definitions[0].selectionSet.selections[0];
getArgumentValues(fieldDef, fieldNode, { stars: 5 }); // => { stars: 5 }
getArgumentValues(fieldDef, fieldNode, {}); // throws an error
export function getArgumentValues(def: GraphQLField<unknown, unknown> | GraphQLDirective, node: FieldNode | DirectiveNode, variableValues?: Maybe<ObjMap<unknown>>): {
[key: string]: unknown;
}

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.

more
less

Note: Returned value is a plain Object with a prototype, since it is exposed to user code. Care should be taken to not pull values from the Object prototype.

@param — - GraphQL schema to use.

@param — - The variable definition AST nodes to coerce.

@param — - The runtime variable values keyed by variable name.

@param — - Optional variable coercion options, including error limits.

@returns — Coerced variable values, or request errors.

@example — ```ts // Coerce provided variables and apply operation defaults. 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' }, );

result; // => { coerced: { stars: 5, limit: 10 } }

@example — ```ts
// This variant uses maxErrors to cap reported coercion errors.
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 },
);
result.errors.length; // => 2
result.errors[1].message; // matches /error limit reached/
export function getVariableValues(schema: GraphQLSchema, varDefNodes: readonly VariableDefinitionNode[], inputs: {
readonly [key: string]: unknown;
}, options?: GetVariableValuesOptions): CoercedVariableValues
Unexported symbols referenced here

Options used when coercing variable values before execution.

more
less

@internal —

interface GetVariableValuesOptions {

Maximum number of variable coercion errors before coercion stops.

more
less

@internal —

maxErrors?: number;
}
Referenced by
type CoercedVariableValues = {
errors: readonly GraphQLError[];
coerced?: never;
} | {
coerced: {
[key: string]: unknown;
};
errors?: never;
}
Referenced by

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.

more
less

If the directive does not exist on the node, returns undefined.

Note: Returned value is a plain Object with a prototype, since it is exposed to user code. Care should be taken to not pull values from the Object prototype.

@param — - The directive definition whose arguments should be coerced.

@param — - The AST node to inspect.

@param — - The runtime variable values keyed by variable name.

@returns — Coerced directive argument values keyed by argument name.

@example — ```ts // 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 }

@example — ```ts
// This variant resolves directive arguments from variables and handles absent directives.
import { parse } from 'graphql/language';
import { GraphQLIncludeDirective } from 'graphql/type';
import { getDirectiveValues } from 'graphql/execution';
const document = parse('query ($includeName: Boolean!) { name
@include — (if: $includeName) }');
const fieldNode = document.definitions[0].selectionSet.selections[0];
getDirectiveValues(GraphQLIncludeDirective, fieldNode, {
includeName: false,
}); // => { if: false }
getDirectiveValues(GraphQLIncludeDirective, { directives: [] }); // => undefined
export function getDirectiveValues(directiveDef: GraphQLDirective, node: DirectiveValuesNode, variableValues?: Maybe<ObjMap<unknown>>): undefined | {
[key: string]: unknown;
}
Unexported symbols referenced here

AST node shape accepted by getDirectiveValues.

more
less

@internal —

interface DirectiveValuesNode {

Directives attached to the AST node.

more
less

@internal —

readonly directives?: readonly DirectiveNode[];
}
Referenced by

Implements the "Subscribe" algorithm described in the GraphQL specification.

more
less

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.

Each payload yielded by the source event stream is executed with the payload as the root value. This maps the subscription source stream into the response stream described by the GraphQL specification.

Accepts an object with named arguments.

@param — - The arguments used to perform the operation.

@returns — A source stream mapped to execution results, or an execution result containing subscription errors.

@example — ```ts // 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' } }

@example — ```ts
// 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' } }

@example — ```ts // This variant shows the error result when the schema has no subscription root. import assert from 'node:assert'; import { parse } from 'graphql/language'; import { buildSchema } from 'graphql/utilities'; import { subscribe } from 'graphql/execution';

const schema = buildSchema( type Query { noop: String });

const result = await subscribe({ schema, document: parse('subscription { greeting }'), });

assert('errors' in result);

result.errors[0].message; // => 'Schema is not configured to execute subscription operation.'

export function subscribe(args: ExecutionArgs): Promise<AsyncGenerator<ExecutionResult, void, void> | ExecutionResult>

Implements the "CreateSourceEventStream" algorithm described in the GraphQL specification, resolving the subscription source event stream.

more
less

Returns a Promise that resolves to either an AsyncIterable (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 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.

@param — - The arguments used to perform the operation.

@returns — The source event stream, or an execution result containing subscription errors.

@example — ```ts import { parse } from 'graphql/language'; import { buildSchema } from 'graphql/utilities'; import { createSourceEventStream } from 'graphql/execution';

async function* greetings() { yield { greeting: 'Hello' }; }

const schema = buildSchema(` type Query { noop: String }

type Subscription { greeting: String } `);

const stream = await createSourceEventStream({ schema, document: parse('subscription { greeting }'), rootValue: { greeting: () => greetings() }, });

Symbol.asyncIterator in stream; // => true

export function createSourceEventStream(args: ExecutionArgs): Promise<AsyncIterable<unknown> | ExecutionResult>

Creates the source event stream for a subscription operation using the legacy positional argument overload. This deprecated overload will be removed in the next major version; use the args object overload instead.

more
less

@param — - GraphQL schema to use.

@param — - The parsed GraphQL document containing the subscription operation.

@param — - Initial root value passed to the subscription resolver.

@param — - Application context value passed to resolvers.

@param — - Runtime variable values keyed by variable name.

@param — - Name of the subscription operation to execute when the document contains multiple operations.

@param — - Resolver used for the root subscription field.

@returns — The source event stream, or an execution result containing subscription errors.

@example — ```ts import { parse } from 'graphql/language'; import { buildSchema } from 'graphql/utilities'; import { createSourceEventStream } from 'graphql/execution';

async function* greetings() { yield { greeting: 'Hello' }; }

const schema = buildSchema(` type Query { noop: String }

type Subscription { greeting: String } `); const document = parse('subscription { greeting }');

const stream = await createSourceEventStream(schema, document, { greeting: () => greetings(), });

Symbol.asyncIterator in stream; // => true

@deprecated — Will be removed in next major version in favor of named arguments.
export function createSourceEventStream(schema: GraphQLSchema, document: DocumentNode, rootValue?: unknown, contextValue?: unknown, variableValues?: Maybe<{
readonly [key: string]: unknown;
}>, operationName?: Maybe<string>, subscribeFieldResolver?: Maybe<GraphQLFieldResolver<any, any>>): Promise<AsyncIterable<unknown> | ExecutionResult>

Arguments accepted by execute and executeSync.

export interface ExecutionArgs {

The schema used for validation or execution.

schema: GraphQLSchema;

The parsed GraphQL document to execute.

document: DocumentNode;

Initial root value passed to the operation.

rootValue?: unknown;

Application context value passed to every resolver.

contextValue?: unknown;

Runtime variable values keyed by variable name.

variableValues?: Maybe<{
readonly [key: string]: unknown;
}>;

Name of the operation to execute when the document contains multiple operations.

operationName?: Maybe<string>;

Resolver used when a field does not define its own resolver.

fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;

Resolver used when an abstract type does not define its own resolver.

typeResolver?: Maybe<GraphQLTypeResolver<any, any>>;

Resolver used for the root subscription field.

subscribeFieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;

Additional execution options.

options?: {

Set the maximum number of errors allowed for coercing (defaults to 50).

maxCoercionErrors?: number;
};
}
Referenced by

Represents the response produced by executing a GraphQL operation.

more
less

@typeParam — TData - Shape of the execution data payload.

@typeParam — TExtensions - Shape of the extensions payload.

export interface ExecutionResult<TData = ObjMap<unknown>, TExtensions = ObjMap<unknown>> {

Errors raised while parsing, validating, or executing the operation.

errors?: readonly GraphQLError[];

Data returned by execution, or null when execution could not produce data.

data?: TData | null;

Extension fields to include in the formatted result.

extensions?: TExtensions;
}
Referenced by

A JSON-serializable GraphQL execution result.

more
less

@typeParam — TData - Shape of the formatted data payload.

@typeParam — TExtensions - Shape of the formatted extensions payload.

export interface FormattedExecutionResult<TData = ObjMap<unknown>, TExtensions = ObjMap<unknown>> {

Errors raised while parsing, validating, or executing the operation.

errors?: readonly GraphQLFormattedError[];

Data returned by execution, or null when execution could not produce data.

data?: TData | null;

Extension fields to include in the formatted result.

extensions?: TExtensions;
}

Deprecated legacy alias for ExecutionArgs retained by the subscription module. Use ExecutionArgs directly instead because SubscriptionArgs will be removed in v17.

more
less

ExecutionArgs has been broadened to include all properties within SubscriptionArgs. The SubscriptionArgs type is retained for backwards compatibility.

@deprecated — use ExecutionArgs instead. Will be removed in v17

export interface SubscriptionArgs extends ExecutionArgs {}

Implements the "Validation" section of the spec.

more
less

Validation runs synchronously, returning an array of encountered errors, or an empty array if no errors were encountered and the document is valid.

A list of specific validation rules may be provided. If not provided, the default list of rules defined by the GraphQL specification will be used.

Each validation rule is a function that returns a visitor (see the language/visitor API). Visitor methods are expected to return GraphQLErrors, or Arrays of GraphQLErrors when invalid.

Validate will stop validation after a maxErrors limit has been reached. Attackers can send pathologically invalid queries to induce a DoS attack, so maxErrors defaults to 100 errors.

Optionally a custom TypeInfo instance may be provided. If not provided, one will be created from the provided schema.

@param — - Schema to validate against.

@param — - Document AST to validate.

@param — - Validation rules to apply.

@param — - Validation options, including error limits.

@param — - TypeInfo instance to update during traversal.

@returns — Validation errors, or an empty array when the document is valid.

@example — ```ts // Validate with the default specified rules. import { parse } from 'graphql/language'; import { buildSchema } from 'graphql/utilities'; import { validate } from 'graphql/validation';

const schema = buildSchema( type Query { greeting: String });

validate(schema, parse('{ greeting }')); // => []

const errors = validate(schema, parse('{ missing }')); errors[0].message; // => 'Cannot query field "missing" on type "Query".'

@example — ```ts
// This variant uses a custom rule list, TypeInfo, and validation options.
import { parse } from 'graphql/language';
import { buildSchema, TypeInfo } from 'graphql/utilities';
import { FieldsOnCorrectTypeRule, validate } from 'graphql/validation';
const schema = buildSchema(`
type Query {
greeting: String
}
`);
const document = parse('{ missingOne missingTwo }');
const errors = validate(
schema,
document,
[FieldsOnCorrectTypeRule],
{ maxErrors: 1 },
new TypeInfo(schema),
);
errors.length; // => 2
errors[1].message; // => 'Too many validation errors, error limit reached. Validation aborted.'
export function validate(schema: GraphQLSchema, documentAST: DocumentNode, rules?: readonly ValidationRule[], options?: ValidationOptions, typeInfo?: TypeInfo): readonly GraphQLError[]
Unexported symbols referenced here

Options used when validating a GraphQL document.

more
less

@internal —

interface ValidationOptions {

Maximum number of validation errors before validation stops.

more
less

@internal —

maxErrors?: number;
}
Referenced by

Validation context passed to query validation rules.

export class ValidationContext extends ASTValidationContext {

Creates a ValidationContext instance.

more
less

@param — - Schema used to validate the document.

@param — - Document AST being validated.

@param — - TypeInfo instance used to track traversal state.

@param — - Callback invoked for each validation error.

@example — ```ts import { parse } from 'graphql/language'; import { GraphQLError } from 'graphql/error'; import { buildSchema, TypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema( type Query { greeting: String }); const document = parse('{ greeting }'); const errors = []; const context = new ValidationContext( schema, document, new TypeInfo(schema), (error) => errors.push(error), );

context.reportError(new GraphQLError('Example validation error.'));

context.getSchema(); // => schema errors[0].message; // => 'Example validation error.'

constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo, onError: (error: GraphQLError) => void)
get [Symbol.toStringTag](): string;

Returns the schema being used by this validation context.

more
less

@returns — The schema being validated against.

@example — ```ts import { parse } from 'graphql/language'; import { buildSchema, TypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema( type Query { greeting: String }); const context = new ValidationContext( schema, parse('{ greeting }'), new TypeInfo(schema), () => {}, );

context.getSchema().getQueryType()?.name; // => 'Query'

getSchema(): GraphQLSchema;

Returns variable usages found directly within this node.

more
less

@param — - The AST node to inspect or visit.

@returns — Variable usages found directly within this node.

@example — ```ts import { parse } from 'graphql/language'; import { buildSchema, TypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema( type Query { greeting(name: String): String }); const document = parse('query ($name: String) { greeting(name: $name) }'); const operation = document.definitions[0]; const context = new ValidationContext( schema, document, new TypeInfo(schema), () => {}, );

const usages = context.getVariableUsages(operation);

usages[0].node.name.value; // => 'name' String(usages[0].type); // => 'String'

getVariableUsages(node: NodeWithSelectionSet): readonly VariableUsage[];

Returns variable usages for an operation, including variables used by referenced fragments.

more
less

@param — - Operation definition to inspect.

@returns — Variable usages reachable from the operation.

@example — ```ts import { parse } from 'graphql/language'; import { buildSchema, TypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema(` type Query { viewer: User }

type User { name(prefix: String): String } ); const document = parse( query ($prefix: String) { viewer { ...UserName } }

fragment UserName on User { name(prefix: $prefix) } `); const operation = document.definitions[0]; const context = new ValidationContext( schema, document, new TypeInfo(schema), () => {}, );

const usages = context.getRecursiveVariableUsages(operation);

usages.map((usage) => usage.node.name.value); // => ['prefix']

getRecursiveVariableUsages(operation: OperationDefinitionNode): readonly VariableUsage[];

Returns the current output type at this point in traversal.

more
less

@returns — The current output type, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema( type Query { greeting: String }); const document = parse('{ greeting }'); const typeInfo = new TypeInfo(schema); const context = new ValidationContext(schema, document, typeInfo, () => {}); let typeName;

visit( document, visitWithTypeInfo(typeInfo, { Field: () => { typeName = String(context.getType()); }, }), );

typeName; // => 'String'

getType(): Maybe<GraphQLOutputType>;

Returns the current parent composite type.

more
less

@returns — The current parent composite type, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema( type Query { greeting: String }); const document = parse('{ greeting }'); const typeInfo = new TypeInfo(schema); const context = new ValidationContext(schema, document, typeInfo, () => {}); let parentTypeName;

visit( document, visitWithTypeInfo(typeInfo, { Field: () => { parentTypeName = context.getParentType()?.name; }, }), );

parentTypeName; // => 'Query'

getParentType(): Maybe<GraphQLCompositeType>;

Returns the current input type at this point in traversal.

more
less

@returns — The current input type, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema( type Query { reviews(limit: Int): [String] }); const document = parse('{ reviews(limit: 5) }'); const typeInfo = new TypeInfo(schema); const context = new ValidationContext(schema, document, typeInfo, () => {}); let inputTypeName;

visit( document, visitWithTypeInfo(typeInfo, { Argument: () => { inputTypeName = String(context.getInputType()); }, }), );

inputTypeName; // => 'Int'

getInputType(): Maybe<GraphQLInputType>;

Returns the parent input type for the current input position.

more
less

@returns — The parent input type, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema(` input ReviewFilter { stars: Int }

type Query { reviews(filter: ReviewFilter): [String] } `); const document = parse('{ reviews(filter: { stars: 5 }) }'); const typeInfo = new TypeInfo(schema); const context = new ValidationContext(schema, document, typeInfo, () => {}); let parentInputTypeName;

visit( document, visitWithTypeInfo(typeInfo, { ObjectField: () => { parentInputTypeName = String(context.getParentInputType()); }, }), );

parentInputTypeName; // => 'ReviewFilter'

getParentInputType(): Maybe<GraphQLInputType>;

Returns the current field definition.

more
less

@returns — The current field definition, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema( type Query { greeting: String }); const document = parse('{ greeting }'); const typeInfo = new TypeInfo(schema); const context = new ValidationContext(schema, document, typeInfo, () => {}); let fieldName;

visit( document, visitWithTypeInfo(typeInfo, { Field: () => { fieldName = context.getFieldDef()?.name; }, }), );

fieldName; // => 'greeting'

getFieldDef(): Maybe<GraphQLField<unknown, unknown>>;

Returns the current directive definition.

more
less

@returns — The current directive definition, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema( type Query { greeting: String }); const document = parse('{ greeting

@include — (if: true) }'); const typeInfo = new TypeInfo(schema); const context = new ValidationContext(schema, document, typeInfo, () => {}); let directiveName;

visit( document, visitWithTypeInfo(typeInfo, { Directive: () => { directiveName = context.getDirective()?.name; }, }), );

directiveName; // => 'include'

getDirective(): Maybe<GraphQLDirective>;

Returns the current argument definition.

more
less

@returns — The current argument definition, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema( type Query { reviews(limit: Int): [String] }); const document = parse('{ reviews(limit: 5) }'); const typeInfo = new TypeInfo(schema); const context = new ValidationContext(schema, document, typeInfo, () => {}); let argumentName;

visit( document, visitWithTypeInfo(typeInfo, { Argument: () => { argumentName = context.getArgument()?.name; }, }), );

argumentName; // => 'limit'

getArgument(): Maybe<GraphQLArgument>;

Returns the current enum value definition.

more
less

@returns — The current enum value definition, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; import { ValidationContext } from 'graphql/validation';

const schema = buildSchema(` enum Sort { NEWEST OLDEST }

type Query { reviews(sort: Sort): [String] } `); const document = parse('{ reviews(sort: OLDEST) }'); const typeInfo = new TypeInfo(schema); const context = new ValidationContext(schema, document, typeInfo, () => {}); let enumValueName;

visit( document, visitWithTypeInfo(typeInfo, { EnumValue: () => { enumValueName = context.getEnumValue()?.name; }, }), );

enumValueName; // => 'OLDEST'

getEnumValue(): Maybe<GraphQLEnumValue>;
}
Referenced by
Unexported symbols referenced here

An instance of this class is passed as the "this" context to all validators, allowing access to commonly useful contextual information from within a validation rule.

more
less

@internal —

class ASTValidationContext {
constructor(ast: DocumentNode, onError: (error: GraphQLError) => void)
get [Symbol.toStringTag](): string;
reportError(error: GraphQLError): void;
getDocument(): DocumentNode;
getFragment(name: string): Maybe<FragmentDefinitionNode>;
getFragmentSpreads(node: SelectionSetNode): readonly FragmentSpreadNode[];
getRecursivelyReferencedFragments(operation: OperationDefinitionNode): readonly FragmentDefinitionNode[];
}
Referenced by
interface VariableUsage {
readonly node: VariableNode;
readonly type: Maybe<GraphQLInputType>;
readonly defaultValue: Maybe<unknown>;
readonly parentType: Maybe<GraphQLInputType>;
}
Referenced by

This set includes all validation rules defined by the GraphQL spec.

more
less

The order of the rules in this list has been adjusted to lead to the most clear output when encountering multiple validation errors.

export const specifiedRules: readonly ValidationRule[] = ...

Technically these aren't part of the spec but they are strongly encouraged validation rules.

export const recommendedRules: readonly typeof MaxIntrospectionDepthRule[] = ...

Executable definitions

more
less

A GraphQL document is only valid for execution if all definitions are either operation or fragment definitions.

See https://spec.graphql.org/draft/#sec-Executable-Definitions

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { ExecutableDefinitionsRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( type Extra { field: String }); const invalidErrors = validate(schema, invalidDocument, [ExecutableDefinitionsRule]);

invalidErrors.length; // => 1

const validDocument = parse( { name }); const validErrors = validate(schema, validDocument, [ExecutableDefinitionsRule]);

validErrors; // => []

export function ExecutableDefinitionsRule(context: ASTValidationContext): ASTVisitor

Fields on correct type

more
less

A GraphQL document is only valid if all fields selected are defined by the parent type, or are an allowed meta field such as __typename.

See https://spec.graphql.org/draft/#sec-Field-Selections

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { FieldsOnCorrectTypeRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( { missing }); const invalidErrors = validate(schema, invalidDocument, [FieldsOnCorrectTypeRule]);

invalidErrors.length; // => 1

const validDocument = parse( { name }); const validErrors = validate(schema, validDocument, [FieldsOnCorrectTypeRule]);

validErrors; // => []

export function FieldsOnCorrectTypeRule(context: ValidationContext): ASTVisitor

Fragments on composite type

more
less

Fragments use a type condition to determine if they apply, since fragments can only be spread into a composite type (object, interface, or union), the type condition must also be a composite type.

See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { FragmentsOnCompositeTypesRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( fragment Bad on String { length }); const invalidErrors = validate(schema, invalidDocument, [FragmentsOnCompositeTypesRule]);

invalidErrors.length; // => 1

const validDocument = parse( fragment Good on Query { name }); const validErrors = validate(schema, validDocument, [FragmentsOnCompositeTypesRule]);

validErrors; // => []

export function FragmentsOnCompositeTypesRule(context: ValidationContext): ASTVisitor

Known argument names

more
less

A GraphQL field is only valid if all supplied arguments are defined by that field.

See https://spec.graphql.org/draft/#sec-Argument-Names See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { KnownArgumentNamesRule } from 'graphql/validation';

const schema = buildSchema( type Query { field(arg: String): String });

const invalidDocument = parse( { field(unknown: "1") }); const invalidErrors = validate(schema, invalidDocument, [KnownArgumentNamesRule]);

invalidErrors.length; // => 1

const validDocument = parse( { field(arg: "1") }); const validErrors = validate(schema, validDocument, [KnownArgumentNamesRule]);

validErrors; // => []

export function KnownArgumentNamesRule(context: ValidationContext): ASTVisitor

Known directives

more
less

A GraphQL document is only valid if all @directives are known by the schema and legally positioned.

See https://spec.graphql.org/draft/#sec-Directives-Are-Defined

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { KnownDirectivesRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse(` { name

@unknown — } `); const invalidErrors = validate(schema, invalidDocument, [KnownDirectivesRule]);

invalidErrors.length; // => 1

const validDocument = parse(` { name

@include — (if: true) } `); const validErrors = validate(schema, validDocument, [KnownDirectivesRule]);

validErrors; // => []

export function KnownDirectivesRule(context: ValidationContext | SDLValidationContext): ASTVisitor
Unexported symbols referenced here

Known fragment names

more
less

A GraphQL document is only valid if all ...Fragment fragment spreads refer to fragments defined in the same document.

See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { KnownFragmentNamesRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( { ...Missing }); const invalidErrors = validate(schema, invalidDocument, [KnownFragmentNamesRule]);

invalidErrors.length; // => 1

const validDocument = parse( fragment NameFields on Query { name } query { ...NameFields }); const validErrors = validate(schema, validDocument, [KnownFragmentNamesRule]);

validErrors; // => []

export function KnownFragmentNamesRule(context: ValidationContext): ASTVisitor

Known type names

more
less

A GraphQL document is only valid if referenced types (specifically variable definitions and fragment conditions) are defined by the type schema.

See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { KnownTypeNamesRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( fragment Bad on Missing { name }); const invalidErrors = validate(schema, invalidDocument, [KnownTypeNamesRule]);

invalidErrors.length; // => 1

const validDocument = parse( fragment Good on Query { name }); const validErrors = validate(schema, validDocument, [KnownTypeNamesRule]);

validErrors; // => []

export function KnownTypeNamesRule(context: ValidationContext | SDLValidationContext): ASTVisitor

Lone anonymous operation

more
less

A GraphQL document is only valid if when it contains an anonymous operation (the query short-hand) that it contains only that one operation definition.

See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { LoneAnonymousOperationRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( query { name } query Other { name }); const invalidErrors = validate(schema, invalidDocument, [LoneAnonymousOperationRule]);

invalidErrors.length; // => 1

const validDocument = parse( { name }); const validErrors = validate(schema, validDocument, [LoneAnonymousOperationRule]);

validErrors; // => []

export function LoneAnonymousOperationRule(context: ASTValidationContext): ASTVisitor

No fragment cycles

more
less

The graph of fragment spreads must not form any cycles including spreading itself. Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data.

See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { NoFragmentCyclesRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( fragment A on Query { ...B } fragment B on Query { ...A } query { ...A }); const invalidErrors = validate(schema, invalidDocument, [NoFragmentCyclesRule]);

invalidErrors.length; // => 1

const validDocument = parse( fragment A on Query { name } query { ...A }); const validErrors = validate(schema, validDocument, [NoFragmentCyclesRule]);

validErrors; // => []

export function NoFragmentCyclesRule(context: ASTValidationContext): ASTVisitor

No undefined variables

more
less

A GraphQL operation is only valid if all variables encountered, both directly and via fragment spreads, are defined by that operation.

See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { NoUndefinedVariablesRule } from 'graphql/validation';

const schema = buildSchema( type Query { field(arg: ID): String });

const invalidDocument = parse( query ($id: ID) { field(arg: $missing) }); const invalidErrors = validate(schema, invalidDocument, [NoUndefinedVariablesRule]);

invalidErrors.length; // => 1

const validDocument = parse( query ($id: ID) { field(arg: $id) }); const validErrors = validate(schema, validDocument, [NoUndefinedVariablesRule]);

validErrors; // => []

export function NoUndefinedVariablesRule(context: ValidationContext): ASTVisitor

No unused fragments

more
less

A GraphQL document is only valid if all fragment definitions are spread within operations, or spread within other fragments spread within operations.

See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { NoUnusedFragmentsRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( fragment Unused on Query { name } query { name }); const invalidErrors = validate(schema, invalidDocument, [NoUnusedFragmentsRule]);

invalidErrors.length; // => 1

const validDocument = parse( fragment Used on Query { name } query { ...Used }); const validErrors = validate(schema, validDocument, [NoUnusedFragmentsRule]);

validErrors; // => []

export function NoUnusedFragmentsRule(context: ASTValidationContext): ASTVisitor

No unused variables

more
less

A GraphQL operation is only valid if all variables defined by an operation are used, either directly or within a spread fragment.

See https://spec.graphql.org/draft/#sec-All-Variables-Used

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { NoUnusedVariablesRule } from 'graphql/validation';

const schema = buildSchema( type Query { field(arg: ID): String name: String });

const invalidDocument = parse( query ($id: ID) { name }); const invalidErrors = validate(schema, invalidDocument, [NoUnusedVariablesRule]);

invalidErrors.length; // => 1

const validDocument = parse( query ($id: ID) { field(arg: $id) }); const validErrors = validate(schema, validDocument, [NoUnusedVariablesRule]);

validErrors; // => []

export function NoUnusedVariablesRule(context: ValidationContext): ASTVisitor

Overlapping fields can be merged

more
less

A selection set is only valid if all fields (including spreading any fragments) either correspond to distinct response names or can be merged without ambiguity.

See https://spec.graphql.org/draft/#sec-Field-Selection-Merging

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { OverlappingFieldsCanBeMergedRule } from 'graphql/validation';

const schema = buildSchema(` type Query { dog: Dog }

type Dog { name: String barkVolume: Int } `);

const invalidDocument = parse( { dog { value: barkVolume value: name } }); const invalidErrors = validate(schema, invalidDocument, [OverlappingFieldsCanBeMergedRule]);

invalidErrors.length; // => 1

const validDocument = parse( { dog { barkVolume name } }); const validErrors = validate(schema, validDocument, [OverlappingFieldsCanBeMergedRule]);

validErrors; // => []

export function OverlappingFieldsCanBeMergedRule(context: ValidationContext): ASTVisitor

Possible fragment spread

more
less

A fragment spread is only valid if the type condition could ever possibly be true: if there is a non-empty intersection of the possible parent types, and possible types which pass the type condition.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { PossibleFragmentSpreadsRule } from 'graphql/validation';

const schema = buildSchema(` type Query { dog: Dog }

type Dog { barkVolume: Int }

type Cat { meowVolume: Int } `);

const invalidDocument = parse( { dog { ... on Cat { meowVolume } } }); const invalidErrors = validate(schema, invalidDocument, [PossibleFragmentSpreadsRule]);

invalidErrors.length; // => 1

const validDocument = parse( { dog { ... on Dog { barkVolume } } }); const validErrors = validate(schema, validDocument, [PossibleFragmentSpreadsRule]);

validErrors; // => []

export function PossibleFragmentSpreadsRule(context: ValidationContext): ASTVisitor

Provided required arguments

more
less

A field or directive is only valid if all required (non-null without a default value) field arguments have been provided.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { ProvidedRequiredArgumentsRule } from 'graphql/validation';

const schema = buildSchema( type Query { field(required: String!): String });

const invalidDocument = parse( { field }); const invalidErrors = validate(schema, invalidDocument, [ProvidedRequiredArgumentsRule]);

invalidErrors.length; // => 1

const validDocument = parse( { field(required: "x") }); const validErrors = validate(schema, validDocument, [ProvidedRequiredArgumentsRule]);

validErrors; // => []

export function ProvidedRequiredArgumentsRule(context: ValidationContext): ASTVisitor

Scalar leafs

more
less

A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { ScalarLeafsRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( { name { length } }); const invalidErrors = validate(schema, invalidDocument, [ScalarLeafsRule]);

invalidErrors.length; // => 1

const validDocument = parse( { name }); const validErrors = validate(schema, validDocument, [ScalarLeafsRule]);

validErrors; // => []

export function ScalarLeafsRule(context: ValidationContext): ASTVisitor

Subscriptions must only include a non-introspection field.

more
less

A GraphQL subscription is valid only if it contains a single root field and that root field is not an introspection field.

See https://spec.graphql.org/draft/#sec-Single-root-field

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { SingleFieldSubscriptionsRule } from 'graphql/validation';

const schema = buildSchema(` type Query { name: String }

type Subscription { a: String b: String } `);

const invalidDocument = parse( subscription { a b }); const invalidErrors = validate(schema, invalidDocument, [SingleFieldSubscriptionsRule]);

invalidErrors.length; // => 1

const validDocument = parse( subscription { a }); const validErrors = validate(schema, validDocument, [SingleFieldSubscriptionsRule]);

validErrors; // => []

export function SingleFieldSubscriptionsRule(context: ValidationContext): ASTVisitor

Unique argument names

more
less

A GraphQL field or directive is only valid if all supplied arguments are uniquely named.

See https://spec.graphql.org/draft/#sec-Argument-Names

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { UniqueArgumentNamesRule } from 'graphql/validation';

const schema = buildSchema( type Query { field(arg: String): String });

const invalidDocument = parse( { field(arg: "1", arg: "2") }); const invalidErrors = validate(schema, invalidDocument, [UniqueArgumentNamesRule]);

invalidErrors.length; // => 1

const validDocument = parse( { field(arg: "1") }); const validErrors = validate(schema, validDocument, [UniqueArgumentNamesRule]);

validErrors; // => []

export function UniqueArgumentNamesRule(context: ASTValidationContext): ASTVisitor

Unique directive names per location

more
less

A GraphQL document is only valid if all non-repeatable directives at a given location are uniquely named.

See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { UniqueDirectivesPerLocationRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse(` { name

@include — (if: true)

@include — (if: false) } `); const invalidErrors = validate(schema, invalidDocument, [UniqueDirectivesPerLocationRule]);

invalidErrors.length; // => 1

const validDocument = parse(` { name

@include — (if: true) } `); const validErrors = validate(schema, validDocument, [UniqueDirectivesPerLocationRule]);

validErrors; // => []

export function UniqueDirectivesPerLocationRule(context: ValidationContext | SDLValidationContext): ASTVisitor

Unique fragment names

more
less

A GraphQL document is only valid if all defined fragments have unique names.

See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { UniqueFragmentNamesRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( fragment A on Query { name } fragment A on Query { name } query { ...A }); const invalidErrors = validate(schema, invalidDocument, [UniqueFragmentNamesRule]);

invalidErrors.length; // => 1

const validDocument = parse( fragment A on Query { name } query { ...A }); const validErrors = validate(schema, validDocument, [UniqueFragmentNamesRule]);

validErrors; // => []

export function UniqueFragmentNamesRule(context: ASTValidationContext): ASTVisitor

Unique input field names

more
less

A GraphQL input object value is only valid if all supplied fields are uniquely named.

See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { UniqueInputFieldNamesRule } from 'graphql/validation';

const schema = buildSchema(` input Filter { name: String }

type Query { search(filter: Filter): String } `);

const invalidDocument = parse( { search(filter: { name: "a", name: "b" }) }); const invalidErrors = validate(schema, invalidDocument, [UniqueInputFieldNamesRule]);

invalidErrors.length; // => 1

const validDocument = parse( { search(filter: { name: "a" }) }); const validErrors = validate(schema, validDocument, [UniqueInputFieldNamesRule]);

validErrors; // => []

export function UniqueInputFieldNamesRule(context: ASTValidationContext): ASTVisitor

Unique operation names

more
less

A GraphQL document is only valid if all defined operations have unique names.

See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { UniqueOperationNamesRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( query Same { name } query Same { name }); const invalidErrors = validate(schema, invalidDocument, [UniqueOperationNamesRule]);

invalidErrors.length; // => 1

const validDocument = parse( query One { name } query Two { name }); const validErrors = validate(schema, validDocument, [UniqueOperationNamesRule]);

validErrors; // => []

export function UniqueOperationNamesRule(context: ASTValidationContext): ASTVisitor

Unique variable names

more
less

A GraphQL operation is only valid if all its variables are uniquely named.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { UniqueVariableNamesRule } from 'graphql/validation';

const schema = buildSchema( type Query { field(arg: ID): String });

const invalidDocument = parse( query ($id: ID, $id: ID) { field(arg: $id) }); const invalidErrors = validate(schema, invalidDocument, [UniqueVariableNamesRule]);

invalidErrors.length; // => 1

const validDocument = parse( query ($id: ID) { field(arg: $id) }); const validErrors = validate(schema, validDocument, [UniqueVariableNamesRule]);

validErrors; // => []

export function UniqueVariableNamesRule(context: ASTValidationContext): ASTVisitor

Value literals of correct type

more
less

A GraphQL document is only valid if all value literals are of the type expected at their position.

See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { ValuesOfCorrectTypeRule } from 'graphql/validation';

const schema = buildSchema( type Query { count(limit: Int): Int });

const invalidDocument = parse( { count(limit: "many") }); const invalidErrors = validate(schema, invalidDocument, [ValuesOfCorrectTypeRule]);

invalidErrors.length; // => 1

const validDocument = parse( { count(limit: 1) }); const validErrors = validate(schema, validDocument, [ValuesOfCorrectTypeRule]);

validErrors; // => []

export function ValuesOfCorrectTypeRule(context: ValidationContext): ASTVisitor

Variables are input types

more
less

A GraphQL operation is only valid if all the variables it defines are of input types (scalar, enum, or input object).

See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { VariablesAreInputTypesRule } from 'graphql/validation';

const schema = buildSchema(` type Query { field(arg: ID): String }

type User { name: String } `);

const invalidDocument = parse( query ($user: User) { field(arg: "1") }); const invalidErrors = validate(schema, invalidDocument, [VariablesAreInputTypesRule]);

invalidErrors.length; // => 1

const validDocument = parse( query ($id: ID) { field(arg: $id) }); const validErrors = validate(schema, validDocument, [VariablesAreInputTypesRule]);

validErrors; // => []

export function VariablesAreInputTypesRule(context: ValidationContext): ASTVisitor

Variables in allowed position

more
less

Variable usages must be compatible with the arguments they are passed to.

See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { VariablesInAllowedPositionRule } from 'graphql/validation';

const schema = buildSchema( type Query { field(arg: ID!): String });

const invalidDocument = parse( query ($id: String) { field(arg: $id) }); const invalidErrors = validate(schema, invalidDocument, [VariablesInAllowedPositionRule]);

invalidErrors.length; // => 1

const validDocument = parse( query ($id: ID!) { field(arg: $id) }); const validErrors = validate(schema, validDocument, [VariablesInAllowedPositionRule]);

validErrors; // => []

export function VariablesInAllowedPositionRule(context: ValidationContext): ASTVisitor

Implements the max introspection depth validation rule.

more
less

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { MaxIntrospectionDepthRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( { __schema { types { fields { type { fields { type { fields { name } } } } } } } }); const invalidErrors = validate(schema, invalidDocument, [MaxIntrospectionDepthRule]);

invalidErrors.length; // => 1

const validDocument = parse( { __schema { queryType { name } } }); const validErrors = validate(schema, validDocument, [MaxIntrospectionDepthRule]);

validErrors; // => []

export function MaxIntrospectionDepthRule(context: ASTValidationContext): ASTVisitor
Referenced by

Lone Schema definition

more
less

A GraphQL document is only valid if it contains only one schema definition.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema } from 'graphql'; import { LoneSchemaDefinitionRule } from 'graphql/validation';

const invalidSDL = schema { query: Query } schema { query: Query } type Query { name: String };

LoneSchemaDefinitionRule.name; // => 'LoneSchemaDefinitionRule' buildSchema(invalidSDL); // throws an error

const validSDL = schema { query: Query } type Query { name: String };

buildSchema(validSDL); // does not throw

export function LoneSchemaDefinitionRule(context: SDLValidationContext): ASTVisitor

Unique operation types

more
less

A GraphQL document is only valid if it has only one type per operation.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema } from 'graphql'; import { UniqueOperationTypesRule } from 'graphql/validation';

const invalidSDL = schema { query: Query query: Other } type Query { name: String } type Other { name: String };

UniqueOperationTypesRule.name; // => 'UniqueOperationTypesRule' buildSchema(invalidSDL); // throws an error

const validSDL = schema { query: Query } type Query { name: String };

buildSchema(validSDL); // does not throw

export function UniqueOperationTypesRule(context: SDLValidationContext): ASTVisitor

Unique type names

more
less

A GraphQL document is only valid if all defined types have unique names.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema } from 'graphql'; import { UniqueTypeNamesRule } from 'graphql/validation';

const invalidSDL = type Query { name: String } type Query { other: String };

UniqueTypeNamesRule.name; // => 'UniqueTypeNamesRule' buildSchema(invalidSDL); // throws an error

const validSDL = type Query { name: String } type Other { name: String };

buildSchema(validSDL); // does not throw

export function UniqueTypeNamesRule(context: SDLValidationContext): ASTVisitor

Unique enum value names

more
less

A GraphQL enum type is only valid if all its values are uniquely named.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema } from 'graphql'; import { UniqueEnumValueNamesRule } from 'graphql/validation';

const invalidSDL = enum Status { ACTIVE ACTIVE } type Query { status: Status };

UniqueEnumValueNamesRule.name; // => 'UniqueEnumValueNamesRule' buildSchema(invalidSDL); // throws an error

const validSDL = enum Status { ACTIVE INACTIVE } type Query { status: Status };

buildSchema(validSDL); // does not throw

export function UniqueEnumValueNamesRule(context: SDLValidationContext): ASTVisitor

Unique field definition names

more
less

A GraphQL complex type is only valid if all its fields are uniquely named.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema } from 'graphql'; import { UniqueFieldDefinitionNamesRule } from 'graphql/validation';

const invalidSDL = type Query { name: String name: String };

UniqueFieldDefinitionNamesRule.name; // => 'UniqueFieldDefinitionNamesRule' buildSchema(invalidSDL); // throws an error

const validSDL = type Query { name: String other: String };

buildSchema(validSDL); // does not throw

export function UniqueFieldDefinitionNamesRule(context: SDLValidationContext): ASTVisitor

Unique argument definition names

more
less

A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. A GraphQL Directive is only valid if all its arguments are uniquely named.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema } from 'graphql'; import { UniqueArgumentDefinitionNamesRule } from 'graphql/validation';

const invalidSDL = type Query { field(arg: String, arg: Int): String };

UniqueArgumentDefinitionNamesRule.name; // => 'UniqueArgumentDefinitionNamesRule' buildSchema(invalidSDL); // throws an error

const validSDL = type Query { field(arg: String): String };

buildSchema(validSDL); // does not throw

export function UniqueArgumentDefinitionNamesRule(context: SDLValidationContext): ASTVisitor

Unique directive names

more
less

A GraphQL document is only valid if all defined directives have unique names.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema } from 'graphql'; import { UniqueDirectiveNamesRule } from 'graphql/validation';

const invalidSDL = ` directive

@tag — on FIELD directive

@tag — on QUERY type Query { name: String } `;

UniqueDirectiveNamesRule.name; // => 'UniqueDirectiveNamesRule' buildSchema(invalidSDL); // throws an error

const validSDL = ` directive

@tag — on FIELD type Query { name: String } `;

buildSchema(validSDL); // does not throw

export function UniqueDirectiveNamesRule(context: SDLValidationContext): ASTVisitor

Possible type extension

more
less

A type extension is only valid if the type is defined and has the same kind.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema } from 'graphql'; import { PossibleTypeExtensionsRule } from 'graphql/validation';

const invalidSDL = extend type Missing { name: String } type Query { name: String };

PossibleTypeExtensionsRule.name; // => 'PossibleTypeExtensionsRule' buildSchema(invalidSDL); // throws an error

const validSDL = type Query { name: String } extend type Query { other: String };

buildSchema(validSDL); // does not throw

export function PossibleTypeExtensionsRule(context: SDLValidationContext): ASTVisitor

No deprecated

more
less

A GraphQL document is only valid if all selected fields and all used enum values have not been deprecated.

Note: This rule is optional and is not part of the Validation section of the GraphQL Specification. The main purpose of this rule is detection of deprecated usages and not necessarily to forbid their use when querying a service.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { GraphQLObjectType, GraphQLSchema, GraphQLString, parse, validate, } from 'graphql'; import { NoDeprecatedCustomRule } from 'graphql/validation';

const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { name: { type: GraphQLString }, oldName: { type: GraphQLString, deprecationReason: 'Use name instead.', }, }, }), });

const invalidDocument = parse( { oldName }); const invalidErrors = validate(schema, invalidDocument, [NoDeprecatedCustomRule]);

invalidErrors.length; // => 1

const validDocument = parse( { name }); const validErrors = validate(schema, validDocument, [NoDeprecatedCustomRule]);

validErrors; // => []

export function NoDeprecatedCustomRule(context: ValidationContext): ASTVisitor

Prohibit introspection queries

more
less

A GraphQL document is only valid if all fields selected are not fields that return an introspection type.

Note: This rule is optional and is not part of the Validation section of the GraphQL Specification. This rule effectively disables introspection, which does not reflect best practices and should only be done if absolutely necessary.

@param — - The validation context used while checking the document.

@returns — A visitor that reports validation errors for this rule.

@example — ```ts import { buildSchema, parse, validate } from 'graphql'; import { NoSchemaIntrospectionCustomRule } from 'graphql/validation';

const schema = buildSchema( type Query { name: String });

const invalidDocument = parse( { __schema { queryType { name } } }); const invalidErrors = validate(schema, invalidDocument, [NoSchemaIntrospectionCustomRule]);

invalidErrors.length; // => 1

const validDocument = parse( { name }); const validErrors = validate(schema, validDocument, [NoSchemaIntrospectionCustomRule]);

validErrors; // => []

export function NoSchemaIntrospectionCustomRule(context: ValidationContext): ASTVisitor

A function that creates an AST visitor for validating a GraphQL document.

export type ValidationRule = (context: ValidationContext) => ASTVisitor
Referenced by

A GraphQLError describes an Error found during the parse, validate, or execute phases of performing a GraphQL operation. In addition to a message and stack trace, it also includes information about the locations in a GraphQL document and/or execution result that correspond to the Error.

export class GraphQLError extends Error {

Creates a GraphQLError instance.

more
less

@param — - Human-readable error message.

@param — - Error metadata such as source locations, response path, original error, and extensions. This positional-arguments constructor overload is deprecated. Use the GraphQLError(message, options) overload instead.

@example — ```ts // Create an error from AST nodes and response metadata. import { parse } from 'graphql/language'; import { GraphQLError } from 'graphql/error';

const document = parse('{ greeting }'); const fieldNode = document.definitions[0].selectionSet.selections[0]; const error = new GraphQLError('Cannot query this field.', { nodes: fieldNode, path: ['greeting'], extensions: { code: 'FORBIDDEN' }, });

error.message; // => 'Cannot query this field.' error.locations; // => [{ line: 1, column: 3 }] error.path; // => ['greeting'] error.extensions; // => { code: 'FORBIDDEN' }

@example — ```ts
// This variant derives locations from source positions and preserves the original error.
import { Source } from 'graphql/language';
import { GraphQLError } from 'graphql/error';
const source = new Source('{ greeting }');
const originalError = new Error('Database unavailable.');
const error = new GraphQLError('Resolver failed.', {
source,
positions: [2],
path: ['greeting'],
originalError,
});
error.locations; // => [{ line: 1, column: 3 }]
error.path; // => ['greeting']
error.originalError; // => originalError
constructor(message: string, options?: GraphQLErrorOptions)

Creates a GraphQLError instance using the legacy positional constructor. This deprecated overload will be removed in v17. Prefer the GraphQLErrorOptions object overload, which keeps optional error metadata in a single options bag.

more
less

@param — - Human-readable error message.

@param — - AST node or nodes associated with this error.

@param — - Source document used to derive error locations.

@param — - Character offsets in the source document associated with this error.

@param — - Response path where this error occurred during execution.

@param — - Original error that caused this GraphQLError, if one exists.

@param — - Extension fields to include in the formatted error.

@example — ```ts import { Source } from 'graphql/language'; import { GraphQLError } from 'graphql/error';

const source = new Source('{ greeting }'); const originalError = new Error('Database unavailable.'); const error = new GraphQLError( 'Resolver failed.', undefined, source, [2], ['greeting'], originalError, { code: 'INTERNAL' }, );

error.locations; // => [{ line: 1, column: 3 }] error.path; // => ['greeting'] error.originalError; // => originalError error.extensions; // => { code: 'INTERNAL' }

@deprecated — Please use the `GraphQLErrorOptions` constructor overload instead.
constructor(message: string, nodes?: readonly ASTNode[] | ASTNode | null, source?: Maybe<Source>, positions?: Maybe<readonly number[]>, path?: Maybe<readonly string | number[]>, originalError?: Maybe<Error & {
readonly extensions?: unknown;
}>, extensions?: Maybe<GraphQLErrorExtensions>)

An array of { line, column } locations within the source GraphQL document which correspond to this error.

more
less

Errors during validation often contain multiple locations, for example to point out two things with the same name. Errors during execution include a single location, the field which produced the error.

Enumerable, and appears in the result of JSON.stringify().

readonly locations: readonly SourceLocation[] | undefined;

An array describing the JSON-path into the execution response which corresponds to this error. Only included for errors during execution.

more
less

Enumerable, and appears in the result of JSON.stringify().

readonly path: readonly string | number[] | undefined;

An array of GraphQL AST Nodes corresponding to this error.

readonly nodes: readonly ASTNode[] | undefined;

The source GraphQL document for the first location of this error.

more
less

Note that if this Error represents more than one node, the source may not represent nodes after the first node.

readonly source: Source | undefined;

An array of character offsets within the source GraphQL document which correspond to this error.

readonly positions: readonly number[] | undefined;

Original error that caused this GraphQLError, if one exists.

readonly originalError: Error | undefined;

Extension fields to add to the formatted error.

readonly extensions: GraphQLErrorExtensions;
get [Symbol.toStringTag](): string;

Returns this error as a human-readable message with source locations.

more
less

@returns — The formatted error string.

@example — ```ts import { Source } from 'graphql/language'; import { GraphQLError } from 'graphql/error';

const error = new GraphQLError('Cannot query field "name".', { source: new Source('{ name }'), positions: [2], });

error.toString(); // => 'Cannot query field "name".\n\nGraphQL request:1:3\n1 | { name }\n | ^'

toString(): string;

Returns the JSON representation used when this object is serialized.

more
less

@returns — The JSON-serializable representation.

@example — ```ts import { GraphQLError } from 'graphql/error';

const error = new GraphQLError('Resolver failed.', { path: ['viewer', 'name'], extensions: { code: 'INTERNAL' }, });

error.toJSON(); // => { message: 'Resolver failed.', path: ['viewer', 'name'], extensions: { code: 'INTERNAL' } }

toJSON(): GraphQLFormattedError;
}
Referenced by

Produces a GraphQLError representing a syntax error, containing useful descriptive information about the syntax error's position in the source.

more
less

@param — - The GraphQL source containing the syntax error.

@param — - Character offset where the syntax error was encountered.

@param — - Human-readable description of the syntax error.

@returns — A GraphQLError located at the syntax error position.

@example — ```ts import { Source } from 'graphql/language'; import { syntaxError } from 'graphql/error';

const error = syntaxError(new Source('query {'), 7, 'Expected Name');

error.message; // => 'Syntax Error: Expected Name' error.locations; // => [{ line: 1, column: 8 }]

export function syntaxError(source: Source, position: number, description: string): GraphQLError

Given an arbitrary value, presumably thrown while attempting to execute a GraphQL operation, produce a new GraphQLError aware of the location in the document responsible for the original Error.

more
less

@param — - The original error value to wrap.

@param — - The AST nodes associated with the error.

@param — - The response path associated with the error.

@returns — The GraphQL error.

@example — ```ts import { parse } from 'graphql/language'; import { locatedError } from 'graphql/error';

const document = parse('{ viewer { name } }'); const fieldNode = document.definitions[0].selectionSet.selections[0]; const error = locatedError(new Error('Resolver failed'), fieldNode, [ 'viewer', ]);

error.message; // => 'Resolver failed' error.locations; // => [{ line: 1, column: 3 }] error.path; // => ['viewer']

export function locatedError(rawOriginalError: unknown, nodes: ASTNode | readonly ASTNode[] | undefined | null, path?: Maybe<readonly string | number[]>): GraphQLError

Prints a GraphQLError to a string, representing useful location information about the error's position in the source. This deprecated helper is retained for backwards compatibility; call error.toString() instead because printError will be removed in v17.

more
less

@param — - The error to format.

@returns — The printed string representation.

@example — ```ts import { GraphQLError, printError } from 'graphql/error';

const message = printError(new GraphQLError('Example error'));

message; // => 'Example error'

@deprecated — Please use `error.toString` instead. Will be removed in v17
export function printError(error: GraphQLError): string

Given a GraphQLError, format it according to the rules described by the Response Format, Errors section of the GraphQL Specification. This deprecated helper is retained for backwards compatibility; call error.toJSON() instead because formatError will be removed in v17.

more
less

@param — - The error to format.

@returns — The JSON-serializable formatted error.

@example — ```ts import { GraphQLError, formatError } from 'graphql/error';

const formatted = formatError(new GraphQLError('Example error'));

formatted; // => { message: 'Example error' }

@deprecated — Please use `error.toJSON` instead. Will be removed in v17
export function formatError(error: GraphQLError): GraphQLFormattedError

Options used to construct a GraphQLError.

export interface GraphQLErrorOptions {

AST node or nodes associated with this error.

nodes?: readonly ASTNode[] | ASTNode | null;

Source document used to derive error locations.

source?: Maybe<Source>;

Character offsets in the source document associated with this error.

positions?: Maybe<readonly number[]>;

Response path where this error occurred during execution.

path?: Maybe<readonly string | number[]>;

Original error that caused this GraphQLError, if one exists.

originalError?: Maybe<Error & {

Extension fields associated with this value.

readonly extensions?: unknown;
}>;

Extension fields to include in the formatted result.

extensions?: Maybe<GraphQLErrorExtensions>;
}
Referenced by

See: https://spec.graphql.org/draft/#sec-Errors

export interface GraphQLFormattedError {

A short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization.

readonly message: string;

If an error can be associated to a particular point in the requested GraphQL document, it should contain a list of locations.

readonly locations?: readonly SourceLocation[];

If an error can be associated to a particular field in the GraphQL result, it must contain an entry with the key path that details the path of the response field which experienced the error. This allows clients to identify whether a null result is intentional or caused by a runtime error.

readonly path?: readonly string | number[];

Reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.

readonly extensions?: GraphQLFormattedErrorExtensions;
}
Referenced by

Custom extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLErrorExtensions {
[key: string]: unknown;
}
Referenced by

Custom formatted extensions

more
less

@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.

export interface GraphQLFormattedErrorExtensions {
[key: string]: unknown;
}
Referenced by

Produce the GraphQL query recommended for a full schema introspection. Accepts optional IntrospectionOptions.

more
less

@param — - Optional configuration for this operation.

@returns — The resolved introspection query.

@example — ```ts // Generate the default introspection query. import { getIntrospectionQuery } from 'graphql/utilities';

const query = getIntrospectionQuery();

query; // matches /__schema/ query; // matches /description/ query; // does not match /specifiedByURL/

@example — ```ts
// This variant customizes optional introspection fields and nesting depth.
import { getIntrospectionQuery } from 'graphql/utilities';
const query = getIntrospectionQuery({
descriptions: false,
specifiedByUrl: true,
directiveIsRepeatable: true,
schemaDescription: true,
inputValueDeprecation: true,
experimentalDirectiveDeprecation: true,
oneOf: true,
typeDepth: 3,
});
query; // does not match /description/
query; // matches /specifiedByURL/
query; // matches /isRepeatable/
query; // matches /includeDeprecated: true/
query; // matches /isOneOf/
(query.match(/ofType/g)?.length ?? 0) > 0; // => true
export function getIntrospectionQuery(options?: IntrospectionOptions): string

Returns an operation AST given a document AST and optionally an operation name. If a name is not provided, an operation is only returned if only one is provided in the document.

more
less

@param — - The parsed GraphQL document AST.

@param — - The optional operation name to select.

@returns — The resolved operation ast.

@example — ```ts import { parse } from 'graphql/language'; import { getOperationAST } from 'graphql/utilities';

const document = parse('query GetName { name }'); const operation = getOperationAST(document, 'GetName');

operation.name.value; // => 'GetName' getOperationAST(document, 'Missing'); // => undefined

export function getOperationAST(documentAST: DocumentNode, operationName?: Maybe<string>): Maybe<OperationDefinitionNode>

Extracts the root type of the operation from the schema. This deprecated helper is retained for backwards compatibility; call GraphQLSchema.getRootType instead because getOperationRootType will be removed in v17.

more
less

@param — - GraphQL schema to use.

@param — - The operation definition to inspect.

@returns — The resolved operation root type.

@example — ```ts import { buildSchema, getOperationRootType } from 'graphql/utilities'; import { parse } from 'graphql/language';

const schema = buildSchema('type Query { name: String }'); const operation = parse('{ name }').definitions[0]; const rootType = getOperationRootType(schema, operation);

rootType.name; // => 'Query'

@deprecated — Please use `GraphQLSchema.getRootType` instead. Will be removed in v17
export function getOperationRootType(schema: GraphQLSchema, operation: OperationDefinitionNode | OperationTypeDefinitionNode): GraphQLObjectType

Build an IntrospectionQuery from a GraphQLSchema

more
less

IntrospectionQuery is useful for utilities that care about type and field relationships, but do not need to traverse through those relationships.

This is the inverse of buildClientSchema. The primary use case is outside of the server context, for instance when doing schema comparisons.

@param — - GraphQL schema to use.

@param — - Optional configuration for this operation.

@returns — Introspection result data for the schema.

@example — ```ts // Include schema metadata using the default introspection options. import { buildSchema, introspectionFromSchema } from 'graphql/utilities';

const schema = buildSchema(` scalar Url

@specifiedBy — (url: "https://url.spec.whatwg.org/")

type Query { homepage: Url } `);

const introspection = introspectionFromSchema(schema); const urlType = introspection.__schema.types.find((type) => type.name === 'Url');

urlType.specifiedByURL; // => 'https://url.spec.whatwg.org/'

@example — ```ts
// This variant disables optional introspection metadata.
import { buildSchema, introspectionFromSchema } from 'graphql/utilities';
const schema = buildSchema(`
scalar Url
@specifiedBy — (url: "https://url.spec.whatwg.org/")
type Query {
homepage: Url
}
`);
const introspection = introspectionFromSchema(schema, {
descriptions: false,
specifiedByUrl: false,
directiveIsRepeatable: false,
schemaDescription: false,
inputValueDeprecation: false,
experimentalDirectiveDeprecation: false,
oneOf: false,
});
const urlType = introspection.__schema.types.find((type) => type.name === 'Url');
const deprecatedDirective = introspection.__schema.directives.find(
(directive) => directive.name === 'deprecated',
);
urlType.specifiedByURL; // => undefined
urlType.description; // => undefined
introspection.__schema.description; // => undefined
deprecatedDirective.isRepeatable; // => undefined
export function introspectionFromSchema(schema: GraphQLSchema, options?: IntrospectionOptions): IntrospectionQuery

Build a GraphQLSchema for use by client tools.

more
less

Given the result of a client running the introspection query, creates and returns a GraphQLSchema instance which can be then used with all graphql-js tools, but cannot be used to execute a query, as introspection does not represent the "resolver", "parse" or "serialize" functions or any other server-internal mechanisms.

This function expects a complete introspection result. Don't forget to check the "errors" field of a server response before calling this function.

@param — - Introspection result data to build from.

@param — - Optional configuration for this operation.

@returns — The client schema represented by the introspection result.

@example — ```ts import { buildClientSchema, introspectionFromSchema, buildSchema } from 'graphql/utilities';

const schema = buildSchema('type Query { hello: String }'); const clientSchema = buildClientSchema(introspectionFromSchema(schema), { assumeValid: true, });

clientSchema.getQueryType().name; // => 'Query'

export function buildClientSchema(introspection: IntrospectionQuery, options?: GraphQLSchemaValidationOptions): GraphQLSchema

Builds a GraphQLSchema from a parsed schema definition language document.

more
less

If no schema definition is provided, then it will look for types named Query, Mutation and Subscription.

The resulting schema has no resolver functions, so execution will use the default field resolver.

@param — - The parsed GraphQL document AST.

@param — - Optional configuration for this operation.

@returns — The schema built from the provided SDL document.

@example — ```ts // Build a schema from a valid parsed SDL document. import { parse } from 'graphql/language'; import { buildASTSchema } from 'graphql/utilities';

const document = parse('type Query { hello: String }'); const schema = buildASTSchema(document);

schema.getQueryType().name; // => 'Query'

@example — ```ts
// This variant uses validation options when the SDL references unknown types.
import { parse } from 'graphql/language';
import { buildASTSchema } from 'graphql/utilities';
const document = parse('type Query { broken: MissingType }');
buildASTSchema(document); // throws an error
buildASTSchema(document, {
assumeValid: true,
assumeValidSDL: true,
}); // does not throw
export function buildASTSchema(documentAST: DocumentNode, options?: BuildSchemaOptions): GraphQLSchema

Builds a GraphQLSchema directly from a schema definition language source.

more
less

@param — - The GraphQL source text or source object.

@param — - Optional configuration for this operation.

@returns — The schema built from the provided SDL document.

@example — ```ts // Build a schema from SDL source using the default options. import { buildSchema } from 'graphql/utilities';

const schema = buildSchema('type Query { hello: String }');

schema.getQueryType().name; // => 'Query'

@example — ```ts
// This variant enables parser options and omits source locations.
import { buildSchema } from 'graphql/utilities';
const schema = buildSchema(
'directive
@tag — on FIELD_DEFINITION\n' +
'directive
@compose —
@tag — on FIELD_DEFINITION',
{
experimentalDirectivesOnDirectiveDefinitions: true,
noLocation: true,
},
);
const directive = schema.getDirective('compose');
directive.name; // => 'compose'
directive.astNode.loc; // => undefined
export function buildSchema(source: string | Source, options?: BuildSchemaOptions & ParseOptions): GraphQLSchema

Produces a new schema given an existing schema and a document which may contain GraphQL type extensions and definitions. The original schema will remain unaltered.

more
less

Because a schema represents a graph of references, a schema cannot be extended without effectively making an entire copy. We do not know until it's too late if subgraphs remain unchanged.

This algorithm copies the provided schema, applying extensions while producing the copy. The original schema remains unaltered.

@param — - GraphQL schema to use.

@param — - The parsed GraphQL document AST.

@param — - Optional configuration for this operation.

@returns — A new schema with the extensions and definitions applied.

@example — ```ts // Extend a schema with new fields and types. import { parse } from 'graphql/language'; import { buildSchema, extendSchema } from 'graphql/utilities';

const schema = buildSchema( type Query { greeting: String }); const extensionAST = parse(` extend type Query { farewell: String }

type Review { body: String } `);

const extendedSchema = extendSchema(schema, extensionAST);

schema.getType('Review'); // => undefined extendedSchema.getType('Review')?.name; // => 'Review' Object.keys(extendedSchema.getQueryType().getFields()); // => ['greeting', 'farewell']

@example — ```ts
// This variant bypasses validation for an otherwise invalid extension.
import { parse } from 'graphql/language';
import { buildSchema, extendSchema } from 'graphql/utilities';
const schema = buildSchema(`
type Query {
greeting: String
}
`);
const invalidExtension = parse(`
extend type Missing {
field: String
}
`);
extendSchema(schema, invalidExtension); // throws an error
extendSchema(schema, invalidExtension, {
assumeValid: true,
assumeValidSDL: true,
}); // does not throw
export function extendSchema(schema: GraphQLSchema, documentAST: DocumentNode, options?: Options): GraphQLSchema
Unexported symbols referenced here
interface Options extends GraphQLSchemaValidationOptions {

Set to true to assume the SDL is valid.

more
less

Default: false

assumeValidSDL?: boolean;
}
Referenced by

Sort GraphQLSchema.

more
less

This function returns a sorted copy of the given GraphQLSchema.

@param — - GraphQL schema to use.

@returns — A copy of the schema with types, fields, arguments, and values sorted lexicographically.

@example — ```ts import { buildSchema, lexicographicSortSchema, printSchema } from 'graphql/utilities';

const schema = buildSchema(` type Query { zebra: String apple: String }

enum Episode { JEDI NEW_HOPE EMPIRE } `);

const sortedSchema = lexicographicSortSchema(schema);

printSchema(sortedSchema); // => // enum Episode { // EMPIRE // JEDI // NEW_HOPE // } // // type Query { // apple: String // zebra: String // }

export function lexicographicSortSchema(schema: GraphQLSchema): GraphQLSchema

Prints the schema.

more
less

@param — - GraphQL schema to use.

@returns — The printed string representation.

@example — ```ts import { buildSchema, printSchema } from 'graphql/utilities';

const schema = buildSchema(` directive

@upper — on FIELD_DEFINITION

type Query { greeting: String

@upper — } `);

printSchema(schema); // => ['directive

@upper — on FIELD_DEFINITION', '', 'type Query {', ' greeting: String', '}'].join('\n')

export function printSchema(schema: GraphQLSchema): string

Prints the type.

more
less

@param — - The GraphQL type to inspect.

@returns — The printed string representation.

@example — ```ts import { buildSchema, printType } from 'graphql/utilities';

const schema = buildSchema(` type User { id: ID! name: String }

type Query { viewer: User } `);

printType(schema.getType('User')); // => ['type User {', ' id: ID!', ' name: String', '}'].join('\n')

export function printType(type: GraphQLNamedType): string

Prints the introspection schema.

more
less

@param — - GraphQL schema to use.

@returns — The printed string representation.

@example — ```ts import { buildSchema, printIntrospectionSchema } from 'graphql/utilities';

const schema = buildSchema( type Query { greeting: String });

const printed = printIntrospectionSchema(schema);

printed; // matches /type __Schema/ printed; // matches /enum __TypeKind/ printed; // does not match /type Query/

export function printIntrospectionSchema(schema: GraphQLSchema): string

Given a Schema and an AST node describing a type, return a GraphQLType definition which applies to that type. For example, if provided the parsed AST node for [User], a GraphQLList instance will be returned, containing the type called "User" found in the schema. If a type called "User" is not found in the schema, then undefined will be returned.

more
less

@param — - GraphQL schema to use.

@param — - The GraphQL type AST node to resolve.

@returns — The GraphQL type referenced by the AST node, or undefined if it cannot be resolved.

@example — ```ts import { parseType } from 'graphql/language'; import { buildSchema, typeFromAST } from 'graphql/utilities';

const schema = buildSchema( type Query { name: String });

typeFromAST(schema, parseType('String'))?.toString(); // => 'String' typeFromAST(schema, parseType('Missing')); // => undefined

export function typeFromAST(schema: GraphQLSchema, typeNode: NamedTypeNode): GraphQLNamedType | undefined

Resolves a list type AST node against a schema.

more
less

@param — - GraphQL schema to use.

@param — - The list type AST node to resolve.

@returns — The GraphQL list type referenced by the AST node, or undefined if it cannot be resolved.

@example — ```ts import { parseType } from 'graphql/language'; import { buildSchema, typeFromAST } from 'graphql/utilities';

const schema = buildSchema( type Query { tags: [String] });

typeFromAST(schema, parseType('[String]'))?.toString(); // => '[String]' typeFromAST(schema, parseType('[Missing]')); // => undefined

export function typeFromAST(schema: GraphQLSchema, typeNode: ListTypeNode): GraphQLList<any> | undefined

Resolves a non-null type AST node against a schema.

more
less

@param — - GraphQL schema to use.

@param — - The non-null type AST node to resolve.

@returns — The GraphQL non-null type referenced by the AST node, or undefined if it cannot be resolved.

@example — ```ts import { parseType } from 'graphql/language'; import { buildSchema, typeFromAST } from 'graphql/utilities';

const schema = buildSchema( type Query { name: String! });

typeFromAST(schema, parseType('String!'))?.toString(); // => 'String!' typeFromAST(schema, parseType('[String!]!'))?.toString(); // => '[String!]!'

export function typeFromAST(schema: GraphQLSchema, typeNode: NonNullTypeNode): GraphQLNonNull<any> | undefined

Resolves a type AST node against a schema.

more
less

@param — - GraphQL schema to use.

@param — - The GraphQL type AST node to resolve.

@returns — The GraphQL type referenced by the AST node, or undefined if it cannot be resolved.

@example — ```ts import { parseType } from 'graphql/language'; import { buildSchema, typeFromAST } from 'graphql/utilities';

const schema = buildSchema(` type User { name: String }

type Query { users: [User!]! } `);

typeFromAST(schema, parseType('User'))?.toString(); // => 'User' typeFromAST(schema, parseType('[User!]!'))?.toString(); // => '[User!]!' typeFromAST(schema, parseType('Missing')); // => undefined

export function typeFromAST(schema: GraphQLSchema, typeNode: TypeNode): GraphQLType | undefined

Produces a JavaScript value given a GraphQL Value AST.

more
less

A GraphQL type must be provided, which will be used to interpret different GraphQL Value literals.

Returns undefined when the value could not be validly coerced according to the provided type.

GraphQL ValueJSON Value
Input ObjectObject
ListArray
BooleanBoolean
StringString
Int / FloatNumber
Enum ValueUnknown
NullValuenull

@param — - GraphQL value AST node to convert.

@param — - The GraphQL type to inspect.

@param — - Optional runtime variable values keyed by variable name.

@returns — The coerced JavaScript value, or undefined if the AST value cannot be coerced to the type.

@example — ```ts // Coerce literal values without variables. import { parseValue } from 'graphql/language'; import { GraphQLInputObjectType, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLString, } from 'graphql/type'; import { valueFromAST } from 'graphql/utilities';

const ReviewInput = new GraphQLInputObjectType({ name: 'ReviewInput', fields: { stars: { type: new GraphQLNonNull(GraphQLInt) }, tags: { type: new GraphQLList(GraphQLString) }, }, });

valueFromAST(parseValue('{ stars: 5, tags: ["featured"] }'), ReviewInput); // => { stars: 5, tags: ['featured'] } valueFromAST(parseValue('{ stars: "bad" }'), ReviewInput); // => undefined

@example — ```ts
// This variant resolves variable references from runtime values.
import { parseValue } from 'graphql/language';
import { GraphQLInt } from 'graphql/type';
import { valueFromAST } from 'graphql/utilities';
valueFromAST(parseValue('$stars'), GraphQLInt, { stars: 5 }); // => 5
valueFromAST(parseValue('$stars'), GraphQLInt, {}); // => undefined
export function valueFromAST(valueNode: Maybe<ValueNode>, type: GraphQLInputType, variables?: Maybe<ObjMap<unknown>>): unknown

Produces a JavaScript value given a GraphQL Value AST.

more
less

Because no GraphQL type is provided, the returned JavaScript value reflects the provided GraphQL value AST.

GraphQL ValueJavaScript Value
Input ObjectObject
ListArray
BooleanBoolean
String / EnumString
Int / FloatNumber
Nullnull

@param — - GraphQL value AST node to convert.

@param — - Optional runtime variable values keyed by variable name.

@returns — JavaScript value represented by the GraphQL value AST.

@example — ```ts import { parseValue } from 'graphql/language'; import { valueFromASTUntyped } from 'graphql/utilities';

const value = valueFromASTUntyped(parseValue('[1, 2, 3]'));

value; // => [1, 2, 3] valueFromASTUntyped(parseValue('$name'), { name: 'Ada' }); // => 'Ada'

export function valueFromASTUntyped(valueNode: ValueNode, variables?: Maybe<ObjMap<unknown>>): unknown

Produces a GraphQL Value AST given a JavaScript object. Function will match JavaScript/JSON values to GraphQL AST schema format by using suggested GraphQLInputType.

more
less

A GraphQL type must be provided, which will be used to interpret different JavaScript values.

JSON ValueGraphQL Value
ObjectInput Object
ArrayList
BooleanBoolean
StringString / Enum Value
NumberInt / Float
UnknownEnum Value
nullNullValue

@param — - Runtime value to convert.

@param — - The GraphQL type to inspect.

@returns — A GraphQL value AST for the provided JavaScript value, or null when no literal can represent it.

@example — ```ts import { print } from 'graphql/language'; import { GraphQLInputObjectType, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLString, } from 'graphql/type'; import { astFromValue } from 'graphql/utilities';

const ReviewInput = new GraphQLInputObjectType({ name: 'ReviewInput', fields: { stars: { type: new GraphQLNonNull(GraphQLInt) }, tags: { type: new GraphQLList(GraphQLString) }, }, });

const valueNode = astFromValue( { stars: 5, tags: ['featured', 'verified'] }, ReviewInput, );

print(valueNode); // => '{ stars: 5, tags: ["featured", "verified"] }' astFromValue(undefined, GraphQLString); // => null astFromValue(null, new GraphQLNonNull(GraphQLString)); // => null

export function astFromValue(value: unknown, type: GraphQLInputType): Maybe<ValueNode>

TypeInfo is a utility class which, given a GraphQL schema, can keep track of the current field and type definitions at any point in a GraphQL document AST during a recursive descent by calling enter(node) and leave(node).

export class TypeInfo {

Creates a TypeInfo instance.

more
less

@param — - Schema used for type lookups.

@param — - Optional type to use at the start of traversal.

@param — - Optional field definition lookup override.

@example — ```ts // Track field types during a visitWithTypeInfo traversal. import { parse, visit } from 'graphql/language'; import { buildSchema } from 'graphql/utilities'; import { TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema( type Query { greeting: String }); const typeInfo = new TypeInfo(schema); const seenTypes = [];

visit( parse('{ greeting }'), visitWithTypeInfo(typeInfo, { Field: () => { seenTypes.push(String(typeInfo.getType())); }, }), );

seenTypes; // => ['String']

@example — ```ts
// This variant starts from an initial type and supplies a field definition resolver.
import { Kind } from 'graphql/language';
import { GraphQLString } from 'graphql/type';
import { buildSchema, TypeInfo } from 'graphql/utilities';
const schema = buildSchema(`
type Query {
greeting: String
}
`);
const typeInfo = new TypeInfo(schema, schema.getQueryType(), () => ({
name: 'virtualGreeting',
description: undefined,
type: GraphQLString,
args: [],
resolve: undefined,
subscribe: undefined,
deprecationReason: undefined,
extensions: Object.create(null),
astNode: undefined,
}));
typeInfo.enter({
kind: Kind.SELECTION_SET,
selections: [],
});
typeInfo.enter({
kind: Kind.FIELD,
name: { kind: Kind.NAME, value: 'ignored' },
});
typeInfo.getFieldDef()?.name; // => 'virtualGreeting'
String(typeInfo.getType()); // => 'String'
constructor(schema: GraphQLSchema, initialType?: Maybe<GraphQLType>, getFieldDefFn?: GetFieldDefFn)
get [Symbol.toStringTag](): string;

Returns the current output type at this point in traversal.

more
less

@returns — The current output type, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema(` type Query { viewer: User }

type User { name: String } `); const typeInfo = new TypeInfo(schema); const fieldTypes = {};

visit( parse('{ viewer { name } }'), visitWithTypeInfo(typeInfo, { Field: (node) => { fieldTypes[node.name.value] = String(typeInfo.getType()); }, }), );

fieldTypes; // => { viewer: 'User', name: 'String' }

getType(): Maybe<GraphQLOutputType>;

Returns the current parent composite type.

more
less

@returns — The current parent composite type, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema(` type Query { viewer: User }

type User { name: String } `); const typeInfo = new TypeInfo(schema); const parentTypes = {};

visit( parse('{ viewer { name } }'), visitWithTypeInfo(typeInfo, { Field: (node) => { parentTypes[node.name.value] = String(typeInfo.getParentType()); }, }), );

parentTypes; // => { viewer: 'Query', name: 'User' }

getParentType(): Maybe<GraphQLCompositeType>;

Returns the current input type at this point in traversal.

more
less

@returns — The current input type, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema(` type Query { reviews(stars: Int!, sort: Sort = NEWEST): [String] }

enum Sort { NEWEST OLDEST } `); const typeInfo = new TypeInfo(schema); const inputTypes = {};

visit( parse('{ reviews(stars: 5, sort: OLDEST) }'), visitWithTypeInfo(typeInfo, { Argument: (node) => { inputTypes[node.name.value] = String(typeInfo.getInputType()); }, }), );

inputTypes; // => { stars: 'Int!', sort: 'Sort' }

getInputType(): Maybe<GraphQLInputType>;

Returns the parent input type for the current input position.

more
less

@returns — The parent input type, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema(` input ReviewFilter { stars: Int! }

type Query { reviews(filter: ReviewFilter): [String] } `); const typeInfo = new TypeInfo(schema); const parentInputTypes = {};

visit( parse('{ reviews(filter: { stars: 5 }) }'), visitWithTypeInfo(typeInfo, { ObjectField: (node) => { parentInputTypes[node.name.value] = String(typeInfo.getParentInputType()); }, }), );

parentInputTypes; // => { stars: 'ReviewFilter' }

getParentInputType(): Maybe<GraphQLInputType>;

Returns the current field definition.

more
less

@returns — The current field definition, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema( type Query { greeting: String }); const typeInfo = new TypeInfo(schema); let fieldName;

visit( parse('{ greeting }'), visitWithTypeInfo(typeInfo, { Field: () => { fieldName = typeInfo.getFieldDef()?.name; }, }), );

fieldName; // => 'greeting'

getFieldDef(): Maybe<GraphQLField<unknown, unknown>>;

Returns the default value for the current input position.

more
less

@returns — The current default value, if one is available.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema( type Query { reviews(limit: Int = 10): [String] }); const typeInfo = new TypeInfo(schema); let defaultLimit;

visit( parse('{ reviews(limit: 5) }'), visitWithTypeInfo(typeInfo, { Argument: () => { defaultLimit = typeInfo.getDefaultValue(); }, }), );

defaultLimit; // => 10

getDefaultValue(): Maybe<unknown>;

Returns the current directive definition.

more
less

@returns — The current directive definition, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema( type Query { greeting: String }); const typeInfo = new TypeInfo(schema); let directiveName;

visit( parse('{ greeting

@include — (if: true) }'), visitWithTypeInfo(typeInfo, { Directive: () => { directiveName = typeInfo.getDirective()?.name; }, }), );

directiveName; // => 'include'

getDirective(): Maybe<GraphQLDirective>;

Returns the current argument definition.

more
less

@returns — The current argument definition, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema( type Query { reviews(limit: Int = 10): [String] }); const typeInfo = new TypeInfo(schema); let argumentName;

visit( parse('{ reviews(limit: 5) }'), visitWithTypeInfo(typeInfo, { Argument: () => { argumentName = typeInfo.getArgument()?.name; }, }), );

argumentName; // => 'limit'

getArgument(): Maybe<GraphQLArgument>;

Returns the current enum value definition.

more
less

@returns — The current enum value definition, if known.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema(` enum Sort { NEWEST OLDEST }

type Query { reviews(sort: Sort = NEWEST): [String] } `); const typeInfo = new TypeInfo(schema); let enumValueName;

visit( parse('{ reviews(sort: OLDEST) }'), visitWithTypeInfo(typeInfo, { EnumValue: () => { enumValueName = typeInfo.getEnumValue()?.name; }, }), );

enumValueName; // => 'OLDEST'

getEnumValue(): Maybe<GraphQLEnumValue>;

Updates this TypeInfo instance for an entered AST node.

more
less

@param — - AST node being entered.

@returns — Nothing.

@example — ```ts import { Kind, parse } from 'graphql/language'; import { buildSchema, TypeInfo } from 'graphql/utilities';

const schema = buildSchema( type Query { greeting: String }); const document = parse('{ greeting }'); const operation = document.definitions[0]; const selectionSet = operation.selectionSet; const field = selectionSet.selections[0]; const typeInfo = new TypeInfo(schema);

typeInfo.enter(operation); typeInfo.enter(selectionSet); typeInfo.enter(field);

field.kind; // => Kind.FIELD typeInfo.getParentType()?.name; // => 'Query' String(typeInfo.getType()); // => 'String'

enter(node: ASTNode): void;

Updates this TypeInfo instance for a left AST node.

more
less

@param — - AST node being entered.

@returns — Nothing.

@example — ```ts import { parse } from 'graphql/language'; import { buildSchema, TypeInfo } from 'graphql/utilities';

const schema = buildSchema( type Query { greeting: String }); const document = parse('{ greeting }'); const operation = document.definitions[0]; const selectionSet = operation.selectionSet; const field = selectionSet.selections[0]; const typeInfo = new TypeInfo(schema);

typeInfo.enter(operation); typeInfo.enter(selectionSet); typeInfo.enter(field); String(typeInfo.getType()); // => 'String'

typeInfo.leave(field); typeInfo.getType(); // => undefined

leave(node: ASTNode): void;
}
Referenced by
Unexported symbols referenced here
type GetFieldDefFn = (schema: GraphQLSchema, parentType: GraphQLType, fieldNode: FieldNode) => Maybe<GraphQLField<unknown, unknown>>
Referenced by

Creates a new visitor instance which maintains a provided TypeInfo instance along with visiting visitor.

more
less

@param — - TypeInfo instance to update during traversal.

@param — - Visitor callbacks to wrap with TypeInfo updates.

@returns — A visitor that keeps TypeInfo in sync while delegating callbacks.

@example — ```ts import { parse, visit } from 'graphql/language'; import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';

const schema = buildSchema( type Query { greeting: String }); const typeInfo = new TypeInfo(schema); const fields = [];

visit( parse('{ greeting }'), visitWithTypeInfo(typeInfo, { Field: (node) => { fields.push({ name: node.name.value, parentType: String(typeInfo.getParentType()), type: String(typeInfo.getType()), }); }, }), );

fields; // => [{ name: 'greeting', parentType: 'Query', type: 'String' }]

export function visitWithTypeInfo(typeInfo: TypeInfo, visitor: ASTVisitor): ASTVisitor

Coerces a JavaScript value given a GraphQL Input Type.

more
less

@param — - JavaScript value to coerce.

@param — - GraphQL input type to coerce the value against.

@param — - Callback invoked for each coercion error.

@returns — Coerced value, or undefined if coercion failed and errors were reported.

@example — ```ts // Coerce runtime input values and throw on invalid input by default. import { GraphQLInputObjectType, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLString, } from 'graphql/type'; import { coerceInputValue } from 'graphql/utilities';

const ReviewInput = new GraphQLInputObjectType({ name: 'ReviewInput', fields: { stars: { type: new GraphQLNonNull(GraphQLInt) }, tags: { type: new GraphQLList(GraphQLString) }, }, });

coerceInputValue({ stars: '5', tags: ['featured'] }, ReviewInput); // => { stars: 5, tags: ['featured'] } coerceInputValue({ stars: 'bad' }, ReviewInput); // throws an error

@example — ```ts
// This variant collects coercion errors with a custom onError callback.
import { GraphQLInt, GraphQLNonNull } from 'graphql/type';
import { coerceInputValue } from 'graphql/utilities';
const errors = [];
const value = coerceInputValue(
null,
new GraphQLNonNull(GraphQLInt),
(path, invalidValue, error) => {
errors.push({ path, invalidValue, message: error.message });
},
);
value; // => undefined
errors; // => [ { path: [], invalidValue: null, message: 'Expected non-nullable type "Int!" not to be null.' } ]
export function coerceInputValue(inputValue: unknown, type: GraphQLInputType, onError?: OnErrorCB): unknown
Unexported symbols referenced here
type OnErrorCB = (path: readonly string | number[], invalidValue: unknown, error: GraphQLError) => void
Referenced by

Provided a collection of ASTs, presumably each from different files, concatenate the ASTs together into batched AST, useful for validating many GraphQL source files which together represent one conceptual application.

more
less

@param — - Document ASTs to concatenate.

@returns — A document AST containing all definitions from the provided documents.

@example — ```ts import { parse } from 'graphql/language'; import { concatAST } from 'graphql/utilities';

const document = concatAST([parse('type Query { a: String }'), parse('type User { id: ID }')]);

document.definitions.length; // => 2

export function concatAST(documents: readonly DocumentNode[]): DocumentNode

separateOperations accepts a single AST document which may contain many operations and fragments and returns a collection of AST documents each of which contains a single operation as well the fragment definitions it refers to.

more
less

@param — - The parsed GraphQL document AST.

@returns — A map of operation names to documents containing each operation and its referenced fragments.

@example — ```ts import { parse, print } from 'graphql/language'; import { separateOperations } from 'graphql/utilities';

const document = parse(` query GetUser { viewer { ...UserFields } }

query GetStatus { status }

fragment UserFields on User { id } `);

const separated = separateOperations(document);

Object.keys(separated); // => ['GetUser', 'GetStatus'] print(separated.GetUser); // matches /fragment UserFields/ print(separated.GetStatus); // does not match /fragment UserFields/

export function separateOperations(documentAST: DocumentNode): ObjMap<DocumentNode>

Strips characters that are not significant to the validity or execution of a GraphQL document:

more
less
  • UnicodeBOM
  • WhiteSpace
  • LineTerminator
  • Comment
  • Comma
  • BlockString indentation

Note: It is required to have a delimiter character between neighboring non-punctuator tokens and this function always uses single space as delimiter.

It is guaranteed that both input and output documents if parsed would result in the exact same AST except for nodes location.

Warning: It is guaranteed that this function will always produce stable results. However, it's not guaranteed that it will stay the same between different releases due to bugfixes or changes in the GraphQL specification.

@param — - The GraphQL source text or source object.

@returns — A semantically equivalent GraphQL source string without ignored characters.

@example — Query source

query SomeQuery($foo: String!, $bar: String) {
someField(foo: $foo, bar: $bar) {
a
b {
c
d
}
}
}

Becomes:

query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}

@example — SDL source

"""
Type description
"""
type Foo {
"""
Field description
"""
bar: String
}

Becomes:

"""Type description""" type Foo{"""Field description""" bar:String}

@example — ```ts import { stripIgnoredCharacters } from 'graphql/utilities';

const source = stripIgnoredCharacters('query Example { name }');

source; // => 'query Example{name}'

export function stripIgnoredCharacters(source: string | Source): string

Provided two types, return true if the types are equal (invariant).

more
less

@param — - The first GraphQL type to compare.

@param — - The second GraphQL type to compare.

@returns — True when both types are equal.

@example — ```ts import { GraphQLList, GraphQLNonNull, GraphQLString, } from 'graphql/type'; import { isEqualType } from 'graphql/utilities';

isEqualType(GraphQLString, GraphQLString); // => true isEqualType(new GraphQLList(GraphQLString), new GraphQLList(GraphQLString)); // => true isEqualType(new GraphQLNonNull(GraphQLString), GraphQLString); // => false

export function isEqualType(typeA: GraphQLType, typeB: GraphQLType): boolean

Provided a type and a super type, return true if the first type is either equal or a subset of the second super type (covariant).

more
less

@param — - GraphQL schema to use.

@param — - The possible subtype to compare.

@param — - The possible supertype to compare.

@returns — True when maybeSubType is equal to or a subtype of superType.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { GraphQLNonNull, assertInterfaceType, assertObjectType, } from 'graphql/type'; import { isTypeSubTypeOf } from 'graphql/utilities';

const schema = buildSchema(` interface Node { id: ID! }

type User implements Node { id: ID! }

type Query { node: Node } `); const Node = assertInterfaceType(schema.getType('Node')); const User = assertObjectType(schema.getType('User'));

isTypeSubTypeOf(schema, User, Node); // => true isTypeSubTypeOf(schema, new GraphQLNonNull(User), Node); // => true isTypeSubTypeOf(schema, Node, User); // => false

export function isTypeSubTypeOf(schema: GraphQLSchema, maybeSubType: GraphQLType, superType: GraphQLType): boolean

Provided two composite types, determine if they "overlap". Two composite types overlap when the Sets of possible concrete types for each intersect.

more
less

This is often used to determine if a fragment of a given type could possibly be visited in a context of another type.

This function is commutative.

@param — - GraphQL schema to use.

@param — - The first GraphQL type to compare.

@param — - The second GraphQL type to compare.

@returns — True when the two composite types can apply to at least one common object type.

@example — ```ts import { buildSchema } from 'graphql/utilities'; import { assertObjectType, assertUnionType } from 'graphql/type'; import { doTypesOverlap } from 'graphql/utilities';

const schema = buildSchema(` type Photo { url: String! }

type Video { url: String! }

union Media = Photo | Video union StillImage = Photo

type Query { media: [Media] } `); const Media = assertUnionType(schema.getType('Media')); const StillImage = assertUnionType(schema.getType('StillImage')); const Video = assertObjectType(schema.getType('Video'));

doTypesOverlap(schema, Media, StillImage); // => true doTypesOverlap(schema, StillImage, Video); // => false

export function doTypesOverlap(schema: GraphQLSchema, typeA: GraphQLCompositeType, typeB: GraphQLCompositeType): boolean

Upholds the spec rules about naming. This deprecated helper is retained for backwards compatibility; call assertName instead because assertValidName will be removed in v17.

more
less

@param — - The GraphQL name to validate.

@returns — The validated GraphQL name.

@example — ```ts import { assertValidName } from 'graphql/utilities';

assertValidName('User'); // => 'User' assertValidName('__typename'); // throws an error

@deprecated — Please use `assertName` instead. Will be removed in v17
export function assertValidName(name: string): string

Returns an Error if a name is invalid. This deprecated helper is retained for backwards compatibility; call assertName and catch the thrown GraphQLError instead because isValidNameError will be removed in v17.

more
less

@param — - The GraphQL name to validate.

@returns — A GraphQLError if the name is invalid; otherwise undefined.

@example — ```ts import { isValidNameError } from 'graphql/utilities';

isValidNameError('User'); // => undefined

const error = isValidNameError('__typename'); error.message; // => 'Name "typename" must not begin with "", which is reserved by GraphQL introspection.'

@deprecated — Please use `assertName` instead. Will be removed in v17
export function isValidNameError(name: string): GraphQLError | undefined

Categories of schema changes that may break existing operations.

export enum BreakingChangeType {

Breaking change code for type removed.

TYPE_REMOVED = "TYPE_REMOVED",

Breaking change code for type changed kind.

TYPE_CHANGED_KIND = "TYPE_CHANGED_KIND",

Breaking change code for type removed from union.

TYPE_REMOVED_FROM_UNION = "TYPE_REMOVED_FROM_UNION",

Breaking change code for value removed from enum.

VALUE_REMOVED_FROM_ENUM = "VALUE_REMOVED_FROM_ENUM",

Breaking change code for required input field added.

REQUIRED_INPUT_FIELD_ADDED = "REQUIRED_INPUT_FIELD_ADDED",

Breaking change code for implemented interface removed.

IMPLEMENTED_INTERFACE_REMOVED = "IMPLEMENTED_INTERFACE_REMOVED",

Breaking change code for field removed.

FIELD_REMOVED = "FIELD_REMOVED",

Breaking change code for field changed kind.

FIELD_CHANGED_KIND = "FIELD_CHANGED_KIND",

Breaking change code for required arg added.

REQUIRED_ARG_ADDED = "REQUIRED_ARG_ADDED",

Breaking change code for arg removed.

ARG_REMOVED = "ARG_REMOVED",

Breaking change code for arg changed kind.

ARG_CHANGED_KIND = "ARG_CHANGED_KIND",

Breaking change code for directive removed.

DIRECTIVE_REMOVED = "DIRECTIVE_REMOVED",

Breaking change code for directive arg removed.

DIRECTIVE_ARG_REMOVED = "DIRECTIVE_ARG_REMOVED",

Breaking change code for required directive arg added.

REQUIRED_DIRECTIVE_ARG_ADDED = "REQUIRED_DIRECTIVE_ARG_ADDED",

Breaking change code for directive repeatable removed.

DIRECTIVE_REPEATABLE_REMOVED = "DIRECTIVE_REPEATABLE_REMOVED",

Breaking change code for directive location removed.

DIRECTIVE_LOCATION_REMOVED = "DIRECTIVE_LOCATION_REMOVED"
}
Referenced by

Categories of schema changes that may be dangerous for existing operations.

export enum DangerousChangeType {

Dangerous change code for value added to enum.

VALUE_ADDED_TO_ENUM = "VALUE_ADDED_TO_ENUM",

Dangerous change code for type added to union.

TYPE_ADDED_TO_UNION = "TYPE_ADDED_TO_UNION",

Dangerous change code for optional input field added.

OPTIONAL_INPUT_FIELD_ADDED = "OPTIONAL_INPUT_FIELD_ADDED",

Dangerous change code for optional arg added.

OPTIONAL_ARG_ADDED = "OPTIONAL_ARG_ADDED",

Dangerous change code for implemented interface added.

IMPLEMENTED_INTERFACE_ADDED = "IMPLEMENTED_INTERFACE_ADDED",

Dangerous change code for arg default value change.

ARG_DEFAULT_VALUE_CHANGE = "ARG_DEFAULT_VALUE_CHANGE"
}
Referenced by

Given two schemas, returns an Array containing descriptions of all the types of breaking changes covered by the other functions down below.

more
less

@param — - Schema before the change.

@param — - Schema after the change.

@returns — Breaking changes between the two schemas.

@example — ```ts import { buildSchema, findBreakingChanges } from 'graphql/utilities';

const oldSchema = buildSchema(` type User { id: ID! name: String }

type Query { viewer: User } ); const newSchema = buildSchema( type User { id: ID! }

type Query { viewer: User } `);

const changes = findBreakingChanges(oldSchema, newSchema);

changes[0].type; // => 'FIELD_REMOVED' changes[0].description; // matches /User.name was removed/

export function findBreakingChanges(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): BreakingChange[]

Given two schemas, returns an Array containing descriptions of all the types of potentially dangerous changes covered by the other functions down below.

more
less

@param — - Schema before the change.

@param — - Schema after the change.

@returns — Dangerous changes between the two schemas.

@example — ```ts import { buildSchema, findDangerousChanges } from 'graphql/utilities';

const oldSchema = buildSchema(` enum Episode { NEW_HOPE }

type Query { episode: Episode } ); const newSchema = buildSchema( enum Episode { NEW_HOPE EMPIRE }

type Query { episode: Episode } `);

const changes = findDangerousChanges(oldSchema, newSchema);

changes[0].type; // => 'VALUE_ADDED_TO_ENUM' changes[0].description; // matches /EMPIRE was added/

export function findDangerousChanges(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): DangerousChange[]

A schema coordinate is resolved in the context of a GraphQL schema to uniquely identify a schema element. It returns undefined if the schema coordinate does not resolve to a schema element, meta-field, or introspection schema element. It will throw if the containing schema element (if applicable) does not exist.

more
less

https://spec.graphql.org/draft/#sec-Schema-Coordinates.Semantics

@param — - GraphQL schema to use.

@param — - The schema coordinate to resolve.

@returns — The schema element identified by the coordinate, or undefined if none exists.

@example — ```ts import { buildSchema, resolveSchemaCoordinate } from 'graphql/utilities';

const schema = buildSchema(` directive

@tag — (name: String!) on FIELD_DEFINITION

input ReviewInput { stars: Int! }

enum Episode { NEW_HOPE }

type Query { reviews(input: ReviewInput): [String]

@tag — (name: "reviews") } `);

resolveSchemaCoordinate(schema, 'Query').kind; // => 'NamedType' resolveSchemaCoordinate(schema, 'Query.reviews').kind; // => 'Field' resolveSchemaCoordinate(schema, 'Query.reviews(input:)').kind; // => 'FieldArgument' resolveSchemaCoordinate(schema, 'ReviewInput.stars').kind; // => 'InputField' resolveSchemaCoordinate(schema, 'Episode.NEW_HOPE').kind; // => 'EnumValue' resolveSchemaCoordinate(schema, '@tag').kind; // => 'Directive' resolveSchemaCoordinate(schema, '@tag(name:)').kind; // => 'DirectiveArgument' resolveSchemaCoordinate(schema, 'Query.missing'); // => undefined

export function resolveSchemaCoordinate(schema: GraphQLSchema, schemaCoordinate: string | Source): ResolvedSchemaElement | undefined

Resolves schema coordinate from a parsed SchemaCoordinate node.

more
less

@param — - GraphQL schema to use.

@param — - The schema coordinate to resolve.

@returns — The schema element identified by the parsed coordinate, or undefined if none exists.

@example — ```ts import { parseSchemaCoordinate } from 'graphql/language'; import { buildSchema, resolveASTSchemaCoordinate } from 'graphql/utilities';

const schema = buildSchema( type Query { greeting(name: String): String }); const coordinate = parseSchemaCoordinate('Query.greeting(name:)'); const resolved = resolveASTSchemaCoordinate(schema, coordinate);

resolved.kind; // => 'FieldArgument' resolved.field.name; // => 'greeting' resolved.fieldArgument.name; // => 'name'

export function resolveASTSchemaCoordinate(schema: GraphQLSchema, schemaCoordinate: SchemaCoordinateNode): ResolvedSchemaElement | undefined

Options controlling which fields are included in the introspection query.

export interface IntrospectionOptions {

Whether to include descriptions in the introspection result. Default: true

descriptions?: boolean;

Whether to include specifiedByURL in the introspection result. Default: false

specifiedByUrl?: boolean;

Whether to include isRepeatable flag on directives. Default: false

directiveIsRepeatable?: boolean;

Whether to include description field on schema. Default: false

schemaDescription?: boolean;

Whether target GraphQL server support deprecation of input values. Default: false

inputValueDeprecation?: boolean;

Whether target GraphQL server supports deprecation of directives. Default: false

experimentalDirectiveDeprecation?: boolean;

Whether target GraphQL server supports @oneOf input objects. Default: false

oneOf?: boolean;

How deep to recurse into nested types, larger values will result in more accurate results, but have a higher load on the server. Some servers might restrict the maximum query depth or complexity. If that's the case, try decreasing this value.

more
less

Default: 9

typeDepth?: number;
}
Referenced by

The result shape returned by a full introspection query.

export interface IntrospectionQuery {

The schema.

readonly __schema: IntrospectionSchema;
}
Referenced by

The introspection representation of a GraphQL schema.

export interface IntrospectionSchema {

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

The root object type used for query operations.

readonly queryType: IntrospectionNamedTypeRef<IntrospectionObjectType>;

The root object type used for mutation operations, if supported.

readonly mutationType: Maybe<IntrospectionNamedTypeRef<IntrospectionObjectType>>;

The root object type used for subscription operations, if supported.

readonly subscriptionType: Maybe<IntrospectionNamedTypeRef<IntrospectionObjectType>>;

Object types that belong to this union type.

readonly types: readonly IntrospectionType[];

Directives available in this schema or applied to this AST node.

readonly directives: readonly IntrospectionDirective[];
}
Referenced by

An introspection type that can appear in input position.

export type IntrospectionInputType = IntrospectionScalarType | IntrospectionEnumType | IntrospectionInputObjectType
Referenced by

An introspection type that can appear in output position.

export type IntrospectionOutputType = IntrospectionScalarType | IntrospectionObjectType | IntrospectionInterfaceType | IntrospectionUnionType | IntrospectionEnumType
Referenced by

The introspection representation of a scalar type.

export interface IntrospectionScalarType {

The introspection kind discriminator for this type reference or type.

readonly kind: "SCALAR";

The GraphQL name for this schema element.

readonly name: string;

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

URL identifying the behavior specified for this custom scalar.

readonly specifiedByURL?: Maybe<string>;
}
Referenced by

The introspection representation of an object type.

export interface IntrospectionObjectType {

The introspection kind discriminator for this type reference or type.

readonly kind: "OBJECT";

The GraphQL name for this schema element.

readonly name: string;

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

Fields declared by this object, interface, input object, or literal.

readonly fields: readonly IntrospectionField[];

Interfaces implemented by this object or interface type.

readonly interfaces: readonly IntrospectionNamedTypeRef<IntrospectionInterfaceType>[];
}
Referenced by

The introspection representation of an interface type.

export interface IntrospectionInterfaceType {

The introspection kind discriminator for this type reference or type.

readonly kind: "INTERFACE";

The GraphQL name for this schema element.

readonly name: string;

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

Fields declared by this object, interface, input object, or literal.

readonly fields: readonly IntrospectionField[];

Interfaces implemented by this object or interface type.

readonly interfaces: readonly IntrospectionNamedTypeRef<IntrospectionInterfaceType>[];

Object types that may be returned for this abstract type.

readonly possibleTypes: readonly IntrospectionNamedTypeRef<IntrospectionObjectType>[];
}
Referenced by

The introspection representation of a union type.

export interface IntrospectionUnionType {

The introspection kind discriminator for this type reference or type.

readonly kind: "UNION";

The GraphQL name for this schema element.

readonly name: string;

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

Object types that may be returned for this abstract type.

readonly possibleTypes: readonly IntrospectionNamedTypeRef<IntrospectionObjectType>[];
}
Referenced by

The introspection representation of an enum type.

export interface IntrospectionEnumType {

The introspection kind discriminator for this type reference or type.

readonly kind: "ENUM";

The GraphQL name for this schema element.

readonly name: string;

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

Values declared by this enum type.

readonly enumValues: readonly IntrospectionEnumValue[];
}
Referenced by

The introspection representation of an input object type.

export interface IntrospectionInputObjectType {

The introspection kind discriminator for this type reference or type.

readonly kind: "INPUT_OBJECT";

The GraphQL name for this schema element.

readonly name: string;

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

Input fields declared by this input object type.

readonly inputFields: readonly IntrospectionInputValue[];

Whether this input object uses the experimental OneOf input object semantics.

readonly isOneOf: boolean;
}
Referenced by

The introspection representation of a named type reference.

more
less

@typeParam — T - The introspection type represented by this named type reference.

export interface IntrospectionNamedTypeRef<T extends IntrospectionType = IntrospectionType> {

The introspection kind discriminator for this type reference or type.

readonly kind: T["kind"];

The GraphQL name for this schema element.

readonly name: string;
}
Referenced by

The introspection representation of a list type reference.

more
less

@typeParam — T - The introspection type reference wrapped by this list type reference.

export interface IntrospectionListTypeRef<T extends IntrospectionTypeRef = IntrospectionTypeRef> {

The introspection kind discriminator for this type reference or type.

readonly kind: "LIST";

The type wrapped by this list or non-null type.

readonly ofType: T;
}
Referenced by

The introspection representation of a non-null type reference.

more
less

@typeParam — T - The introspection type reference wrapped by this non-null type reference.

export interface IntrospectionNonNullTypeRef<T extends IntrospectionTypeRef = IntrospectionTypeRef> {

The introspection kind discriminator for this type reference or type.

readonly kind: "NON_NULL";

The type wrapped by this list or non-null type.

readonly ofType: T;
}
Referenced by

The introspection representation of a field.

export interface IntrospectionField {

The GraphQL name for this schema element.

readonly name: string;

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

Arguments accepted by this field or directive.

readonly args: readonly IntrospectionInputValue[];

The GraphQL type reference or runtime type for this element.

readonly type: IntrospectionOutputTypeRef;

Whether this field, argument, enum value, or input value is deprecated.

readonly isDeprecated: boolean;

Reason this element is deprecated, if one was provided.

readonly deprecationReason: Maybe<string>;
}
Referenced by

The introspection representation of an argument or input field.

export interface IntrospectionInputValue {

The GraphQL name for this schema element.

readonly name: string;

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

The GraphQL type reference or runtime type for this element.

readonly type: IntrospectionInputTypeRef;

Default value used when no explicit value is supplied.

readonly defaultValue: Maybe<string>;

Whether this field, argument, enum value, or input value is deprecated.

readonly isDeprecated?: boolean;

Reason this element is deprecated, if one was provided.

readonly deprecationReason?: Maybe<string>;
}
Referenced by

The introspection representation of an enum value.

export interface IntrospectionEnumValue {

The GraphQL name for this schema element.

readonly name: string;

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

Whether this field, argument, enum value, or input value is deprecated.

readonly isDeprecated: boolean;

Reason this element is deprecated, if one was provided.

readonly deprecationReason: Maybe<string>;
}
Referenced by

The introspection representation of a directive.

export interface IntrospectionDirective {

The GraphQL name for this schema element.

readonly name: string;

Human-readable description for this schema element, if provided.

readonly description?: Maybe<string>;

Whether this directive may appear more than once at the same location.

readonly isRepeatable?: boolean;

Whether this field, argument, enum value, or input value is deprecated.

readonly isDeprecated?: boolean;

Reason this element is deprecated, if one was provided.

readonly deprecationReason?: Maybe<string>;

Locations where this directive may be applied.

readonly locations: readonly DirectiveLocation[];

Arguments accepted by this field or directive.

readonly args: readonly IntrospectionInputValue[];
}
Referenced by

Options used when building a schema from SDL or a parsed SDL document.

export interface BuildSchemaOptions extends GraphQLSchemaValidationOptions {

Set to true to assume the SDL is valid.

more
less

Default: false

assumeValidSDL?: boolean;
}
Referenced by

Description of a schema change that may break existing operations.

export interface BreakingChange {

Specific kind of breaking schema change.

type: BreakingChangeType;

Human-readable description of the breaking schema change.

description: string;
}
Referenced by

Description of a schema change that may be dangerous for existing operations.

export interface DangerousChange {

Specific kind of dangerous schema change.

type: DangerousChangeType;

Human-readable description of the dangerous schema change.

description: string;
}
Referenced by

Wrapper type that contains DocumentNode and types that can be deduced from it.

more
less

@typeParam — TResponseData - Typed GraphQL response data shape.

@typeParam — TRequestVariables - Typed GraphQL request variables shape.

export interface TypedQueryDocumentNode<TResponseData = {
[key: string]: any;
}, TRequestVariables = {
[key: string]: any;
}> extends DocumentNode {

Top-level executable and type-system definitions in this document.

readonly definitions: readonly ExecutableDefinitionNode[];

This type is used to ensure that the variables you pass in to the query are assignable to Variables and that the Result is assignable to whatever you pass your result to. The method is never actually implemented, but the type is valid because we list it as optional

__ensureTypesOfVariablesAndResultMatching?: (variables: TRequestVariables) => TResponseData;
}

A schema element resolved from a schema coordinate.

export type ResolvedSchemaElement = ResolvedNamedType | ResolvedField | ResolvedInputField | ResolvedEnumValue | ResolvedFieldArgument | ResolvedDirective | ResolvedDirectiveArgument
Referenced by
Unexported symbols referenced here

A resolved schema element may be one of the following kinds:

more
less

@internal —

interface ResolvedNamedType {
readonly kind: "NamedType";
readonly type: GraphQLNamedType;
}
Referenced by

@internal —

interface ResolvedField {
readonly kind: "Field";
readonly field: GraphQLField<unknown, unknown>;
}
Referenced by

@internal —

interface ResolvedInputField {
readonly kind: "InputField";
readonly type: GraphQLInputObjectType;
readonly inputField: GraphQLInputField;
}
Referenced by

@internal —

interface ResolvedEnumValue {
readonly kind: "EnumValue";
readonly type: GraphQLEnumType;
readonly enumValue: GraphQLEnumValue;
}
Referenced by

@internal —

interface ResolvedFieldArgument {
readonly kind: "FieldArgument";
readonly field: GraphQLField<unknown, unknown>;
readonly fieldArgument: GraphQLArgument;
}
Referenced by

@internal —

interface ResolvedDirective {
readonly kind: "Directive";
readonly directive: GraphQLDirective;
}
Referenced by

@internal —

interface ResolvedDirectiveArgument {
readonly kind: "DirectiveArgument";
readonly directive: GraphQLDirective;
readonly directiveArgument: GraphQLArgument;
}
Referenced by
}