@category — Version
A string containing the version of the GraphQL.js library
An object containing the components of the GraphQL.js version string
export const versionInfo: Readonly<{Describes the input object accepted by graphql and graphqlSync.
These arguments describe the full parse, validate, and execute lifecycle for a GraphQL request.
@category — Request Pipeline
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.
Use this for shared request data such as the currently logged in user and connections to databases or other services.
A mapping of variable name to runtime value for variables defined by the operation.
variableValues?: Maybe<{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.
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.
A type resolver function to use when none is provided by the schema.
If not provided, the default type resolver is used, which looks for a
__typename field or alternatively calls the isTypeOf method.
Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/
@internal —
Parses, validates, and executes a GraphQL document against a schema.
This is the primary entry point for fulfilling GraphQL operations. Use this when you want a single-call request lifecycle that returns a promise in all cases.
More sophisticated GraphQL servers, such as those which persist queries, may wish to separate the validation and execution phases to a static-time tooling step and a server runtime step.
@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
Parses, validates, and executes a GraphQL document synchronously.
This function guarantees that execution completes synchronously, or throws an error, assuming that all field resolvers are also synchronous. It throws when any resolver returns a promise.
@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
Resolves a thunked object map.
@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
@internal —
interface ObjMap<T> {Resolves a thunked readonly array.
@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]
Schema Definition
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 reachableby traversing the root types are included, other types must be explicitlyreferenced.```tsconst 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]),});
Creates a GraphQLSchema instance.
@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: Querymutation: Mutationsubscription: 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(); // => Mutationschema.getSubscriptionType(); // => Subscriptionschema.getType('AuditEvent'); // => AuditEventschema.getDirective('auth'); // => authDirectiveschema.extensions; // => { owner: 'platform' }
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.
@internal —
Returns the root object type for query operations.
@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'
Returns the root object type for mutation operations.
@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'
Returns the root object type for subscription operations.
@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'
Returns the root object type for the requested operation kind.
@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
Returns all named types known to this schema.
@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'
Returns the named type with the provided name.
@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
Returns object types that may be returned for an abstract type.
@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']
Returns objects and interfaces that implement an interface type.
@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']
Returns whether one type is a possible runtime subtype of an abstract type.
@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
Returns directives available in this schema.
@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']
Returns the current directive definition.
@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
Returns a normalized configuration object for this object.
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'
@internal —
interface GraphQLSchemaNormalizedConfig extends GraphQLSchemaConfig {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.
@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' }
The GraphQL name for this schema element.
name: string;Whether this directive may appear more than once at the same location.
isRepeatable: boolean;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[];Returns a normalized configuration object for this object.
@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'
Returns the schema coordinate identifying this directive.
@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'
Returns the JSON representation used when this object is serialized.
@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"}'
Scalar Type Definition
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;
} });
Creates a GraphQLScalarType instance.
@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 }
The GraphQL name for this schema element.
name: 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>;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[];Returns a normalized configuration object for this object.
@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
Returns the schema coordinate identifying this scalar type.
@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'
Returns the JSON representation used when this object is serialized.
@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"}'
Object Type Definition
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 toitself in a field, you can use a function expression (aka a closure or athunk) to supply the fields lazily.```tsconst PersonType = new GraphQLObjectType({name: 'Person',fields: () => ({name: { type: GraphQLString },bestFriend: { type: PersonType },})});
Creates a GraphQLObjectType instance.
@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'
The GraphQL name for this schema element.
name: 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[];Returns the fields defined by this type.
@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!'
Returns the interfaces implemented by this type.
@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']
Returns a normalized configuration object for this object.
@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
Returns the schema coordinate identifying this object type.
@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'
Returns the JSON representation used when this object is serialized.
@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"}'
Interface Type Definition
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 } } });
Creates a GraphQLInterfaceType instance.
@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 }
The GraphQL name for this schema element.
name: string;Function that resolves the concrete object type for this abstract type.
resolveType: Maybe<GraphQLTypeResolver<any, any>>;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[];Returns the fields defined by this type.
@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!'
Returns the interfaces implemented by this type.
@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']
Returns a normalized configuration object for this object.
@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!'
Returns the schema coordinate identifying this interface type.
@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'
Returns the JSON representation used when this object is serialized.
@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"}'
@internal —
interface GraphQLInterfaceTypeNormalizedConfig extends GraphQLInterfaceTypeConfig<any, any> { }Union Type Definition
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; } } });
Creates a GraphQLUnionType instance.
@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 }
The GraphQL name for this schema element.
name: string;Function that resolves the concrete object type for this abstract type.
resolveType: Maybe<GraphQLTypeResolver<any, any>>;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[];Returns the object types included in this union.
@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']
Returns a normalized configuration object for this object.
@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']
Returns the schema coordinate identifying this union type.
@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'
Returns the JSON representation used when this object is serialized.
@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"}'
Enum Type Definition
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 valuewill be used as its internal value.
Creates a GraphQLEnumType instance.
@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' }
The GraphQL name for this schema element.
name: string;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[];Returns the values defined by this enum type.
@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']
Returns the enum value definition for a value name.
@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
Serializes a runtime enum value as a GraphQL enum name.
@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
Parses a GraphQL enum name from variable input.
@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
Parses a GraphQL enum name from an AST value literal.
@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
Returns a normalized configuration object for this object.
@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'
Returns the schema coordinate identifying this enum type.
@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'
Returns the JSON representation used when this object is serialized.
@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"}'
Input Object Type Definition
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 }, } });
Creates a GraphQLInputObjectType instance.
@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
The GraphQL name for this schema element.
name: string;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;Returns the fields defined by this type.
@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; // => ''
Returns a normalized configuration object for this object.
@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!'
Returns the schema coordinate identifying this input object type.
@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'
Returns the JSON representation used when this object is serialized.
@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"}'
List Type Wrapper
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) }, }) })
Creates a GraphQLList instance.
@param — - The type to wrap.
@example — ```ts import { GraphQLList, GraphQLString } from 'graphql/type';
const stringList = new GraphQLList(GraphQLString);
stringList.ofType; // => GraphQLString String(stringList); // => '[String]'
The type wrapped by this list or non-null type.
readonly ofType: T;Returns this wrapping type as a GraphQL type-reference string.
@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!]'
Returns the JSON representation used when this object is serialized.
@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]"}'
Non-Null Type Wrapper
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.
Creates a GraphQLNonNull instance.
@param — - The type to wrap.
@example — ```ts import { GraphQLNonNull, GraphQLString } from 'graphql/type';
const requiredString = new GraphQLNonNull(GraphQLString);
requiredString.ofType; // => GraphQLString String(requiredString); // => 'String!'
The type wrapped by this list or non-null type.
readonly ofType: T;Returns this wrapping type as a GraphQL type-reference string.
@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]!'
Returns the JSON representation used when this object is serialized.
@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!"}'
All built-in scalar types defined by the GraphQL specification.
export const specifiedScalarTypes: readonly GraphQLScalarType[] = ...The built-in Boolean scalar type.
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.
The optional reason argument defaults to DEFAULT_DEPRECATION_REASON.
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.
@category — Introspection
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 directive.
export const __Directive: GraphQLObjectType = ...The introspection enum describing directive locations.
export const __DirectiveLocation: GraphQLEnumType = ...The introspection type describing object and interface fields.
export const __Field: GraphQLObjectType = ...The introspection type describing arguments and input fields.
export const __InputValue: GraphQLObjectType = ...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.
The __typename meta field definition used by execution and introspection.
Test if the given value is a GraphQL schema.
@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
Test if the given value is a GraphQL directive.
@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
Returns true when the value is any GraphQL type.
@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
There are predicates for each kind of GraphQL type.
@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
Returns true when the value is a GraphQLObjectType.
@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
Returns true when the value is a GraphQLInterfaceType.
@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
Returns true when the value is a GraphQLUnionType.
@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
Returns true when the value is a GraphQLEnumType.
@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
Returns true when the value is a GraphQLInputObjectType.
@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
Returns true when the value is a GraphQLList.
@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
Returns true when the output type is a GraphQLList.
@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
Returns true when the value is a GraphQLList.
@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
Returns true when the value is a GraphQLNonNull.
@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
Returns true when the output type is a GraphQLNonNull.
@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
Returns true when the value is a GraphQLNonNull.
@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
Returns true when the value can be used as a GraphQL input type.
@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
Returns true when the value can be used as a GraphQL output type.
@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
Returns true when the value is a GraphQL scalar or enum type.
@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
Returns true when the value is a GraphQL object, interface, or union type.
@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
Returns true when the value is a GraphQL interface or union type.
@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
Returns true when the value is a GraphQL list or non-null wrapper type.
@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
Returns true when the value is a GraphQL type that can accept null.
@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
Returns true when the value is a GraphQL named type.
@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
Returns true when the argument is non-null and has no default value.
@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
Returns true when the input field is non-null and has no default value.
@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
Returns true when the scalar type is one of the scalars specified by GraphQL.
@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
Returns true when the type is one of the built-in introspection types.
@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
Returns true when the directive is one of the directives specified by GraphQL.
@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
Returns the value as a GraphQLSchema, or throws if it is not a schema.
@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
Returns the value as a GraphQLDirective, or throws if it is not a directive.
@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
Returns the value as a GraphQL type, or throws if it is not one.
@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
Returns the value as a GraphQLScalarType, or throws if it is not one.
@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
Returns the value as a GraphQLObjectType, or throws if it is not one.
@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
Returns the value as a GraphQLInterfaceType, or throws if it is not one.
@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
Returns the value as a GraphQLUnionType, or throws if it is not one.
@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
Returns the value as a GraphQLEnumType, or throws if it is not one.
@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
Returns the value as a GraphQLInputObjectType, or throws if it is not one.
@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
Returns the value as a GraphQLList, or throws if it is not one.
@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
Returns the value as a GraphQLNonNull, or throws if it is not one.
@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
Returns the value as a GraphQL input type, or throws if it is not one.
@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
Returns the value as a GraphQL output type, or throws if it is not one.
@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
Returns the value as a GraphQL leaf type, or throws if it is not one.
@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
Returns the value as a GraphQL composite type, or throws if it is not one.
@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
Returns the value as a GraphQL abstract type, or throws if it is not one.
@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
Returns the value as a GraphQL wrapping type, or throws if it is not one.
@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
Returns the value as a nullable GraphQL type, or throws if it is not one.
@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
Returns the value as a GraphQL named type, or throws if it is not one.
@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
Returns the nullable type.
@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
Returns the nullable type after removing one non-null wrapper.
@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
Returns the nullable type after removing one non-null wrapper.
@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
Returns the named type.
@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
Returns the named input type after unwrapping all list and non-null wrappers.
@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'
Returns the named output type after unwrapping all list and non-null wrappers.
@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'
Returns the named type after unwrapping all list and non-null wrappers.
@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
Returns the named type after unwrapping all list and non-null wrappers.
@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
Implements the "Type Validation" sub-sections of the specification's "Type System" section.
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; // => []
Utility function which asserts a schema is valid by throwing an error if it is invalid.
@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
@category — Names
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
Upholds the spec rules about naming enum values.
@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
These are all of the possible kinds of types.
export type GraphQLType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLType> | GraphQLNonNull<GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLType>>These types may be used as input types for arguments and directives.
export type GraphQLInputType = GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLInputType> | GraphQLNonNull<GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLInputType>>These types may be used as output types as the result of fields.
export type GraphQLOutputType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList<GraphQLOutputType> | GraphQLNonNull<GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList<GraphQLOutputType>>These types may describe types which may be leaf values.
export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumTypeThese types may describe the parent context of a selection set.
export type GraphQLCompositeType = GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionTypeThese types may describe the parent context of a selection set.
export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionTypeThese types wrap and modify other types
export type GraphQLWrappingType = GraphQLList<GraphQLType> | GraphQLNonNull<GraphQLType>These types can all accept null as a value.
export type GraphQLNullableType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLType>These named types do not include modifiers like List or NonNull.
export type GraphQLNamedType = GraphQLNamedInputType | GraphQLNamedOutputTypeA named GraphQL type that can be used as an input type.
export type GraphQLNamedInputType = GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectTypeA named GraphQL type that can be used as an output type.
export type GraphQLNamedOutputType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumTypeUsed while defining GraphQL types to allow for circular references in otherwise immutable type definitions.
@typeParam — T - The element type returned by the thunk or array.
Configuration used to construct a GraphQLSchema.
export interface GraphQLSchemaConfig extends GraphQLSchemaValidationOptions {Directives available in this schema or applied to this AST node.
directives?: Maybe<readonly GraphQLDirective[]>;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[]>;@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.
Default: false
Custom extensions
@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.
Configuration used to construct a GraphQLDirective.
export interface GraphQLDirectiveConfig {The GraphQL name for this schema element.
name: string;Whether this directive may appear more than once at the same location.
isRepeatable?: Maybe<boolean>;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[]>;Custom extensions
@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.
A resolved GraphQL argument definition.
export interface GraphQLArgument {The GraphQL name for this schema element.
name: string;Default value used when no explicit value is supplied.
defaultValue: unknown;AST node from which this schema element was built, if available.
astNode: Maybe<InputValueDefinitionNode>;Configuration used to define a GraphQL argument.
export interface GraphQLArgumentConfig {Default value used when no explicit value is supplied.
defaultValue?: unknown;AST node from which this schema element was built, if available.
astNode?: Maybe<InputValueDefinitionNode>;Custom extensions
@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.
Configuration used to construct a GraphQLEnumType.
export interface GraphQLEnumTypeConfig {The GraphQL name for this schema element.
name: string;Values contained in this enum, list, or input-object definition.
values: ThunkObjMap<GraphQLEnumValueConfig>;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[]>;Custom extensions
@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.
A resolved GraphQL enum value definition.
export interface GraphQLEnumValue {The GraphQL name for this schema element.
name: string;Parsed value represented by this node.
value: any;AST node from which this schema element was built, if available.
astNode: Maybe<EnumValueDefinitionNode>;Configuration used to define a GraphQL enum value.
export interface GraphQLEnumValueConfig {Parsed value represented by this node.
value?: any;Custom extension fields reserved for users.
extensions?: Maybe<Readonly<GraphQLEnumValueExtensions>>;AST node from which this schema element was built, if available.
astNode?: Maybe<EnumValueDefinitionNode>;A map of enum value names to enum value configuration objects.
export type GraphQLEnumValueConfigMap = ObjMap<GraphQLEnumValueConfig>Custom extensions
@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.
A resolved GraphQL field definition.
@typeParam — TSource - Source object type passed to resolvers.
@typeParam — TContext - Context object type passed to resolvers.
@typeParam — TArgs - Argument object type passed to resolvers.
The GraphQL name for this schema element.
name: string;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>;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>;Configuration used to define a GraphQL field.
@typeParam — TSource - Source object type passed to resolvers.
@typeParam — TContext - Context object type passed to resolvers.
@typeParam — TArgs - Argument object type passed to resolvers.
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>;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>;A map of argument names to argument configuration objects.
export type GraphQLFieldConfigArgumentMap = ObjMap<GraphQLArgumentConfig>A map of field names to field configuration objects.
@typeParam — TSource - Source object type passed to resolvers.
@typeParam — TContext - Context object type passed to resolvers.
Custom extensions
@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.
A map of field names to resolved field definitions.
@typeParam — TSource - Source object type passed to resolvers.
@typeParam — TContext - Context object type passed to resolvers.
Resolves the runtime value for a GraphQL field.
@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.
A resolved GraphQL input field definition.
export interface GraphQLInputField {The GraphQL name for this schema element.
name: string;Default value used when no explicit value is supplied.
defaultValue: unknown;AST node from which this schema element was built, if available.
astNode: Maybe<InputValueDefinitionNode>;Configuration used to define a GraphQL input field.
export interface GraphQLInputFieldConfig {Default value used when no explicit value is supplied.
defaultValue?: unknown;Custom extension fields reserved for users.
extensions?: Maybe<Readonly<GraphQLInputFieldExtensions>>;AST node from which this schema element was built, if available.
astNode?: Maybe<InputValueDefinitionNode>;A map of input field names to input field configuration objects.
export type GraphQLInputFieldConfigMap = ObjMap<GraphQLInputFieldConfig>Custom extensions
@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.
A map of input field names to resolved input field definitions.
export type GraphQLInputFieldMap = ObjMap<GraphQLInputField>Configuration used to construct a GraphQLInputObjectType.
export interface GraphQLInputObjectTypeConfig {The GraphQL name for this schema element.
name: 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;Custom extensions
@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.
Configuration used to construct a GraphQLInterfaceType.
@typeParam — TSource - Source object type passed to resolvers.
@typeParam — TContext - Context object type passed to resolvers.
The GraphQL name for this schema element.
name: 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.
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[]>;Custom extensions
@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.
Checks whether a runtime value belongs to a GraphQL object type.
@typeParam — TSource - Source object type tested against this object type.
@typeParam — TContext - Context object type passed to resolvers.
Configuration used to construct a GraphQLObjectType.
@typeParam — TSource - Source object type passed to resolvers.
@typeParam — TContext - Context object type passed to resolvers.
The GraphQL name for this schema element.
name: 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[]>;Custom extensions
@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.
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[];Fragment definitions in the operation document keyed by fragment name.
readonly fragments: ObjMap<FragmentDefinitionNode>;Initial root value passed to the operation.
readonly rootValue: unknown;Runtime variable values keyed by variable name.
readonly variableValues: {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;Configuration used to construct a GraphQLScalarType.
@typeParam — TInternal - The internal runtime representation accepted by this scalar.
@typeParam — TExternal - The serialized representation exposed in GraphQL results.
The GraphQL name for this schema element.
name: 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[]>;Custom extensions
@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.
Resolves the concrete object type for an abstract GraphQL type.
@typeParam — TSource - Source object type passed to resolvers.
@typeParam — TContext - Context object type passed to resolvers.
Configuration used to construct a GraphQLUnionType.
@typeParam — TSource - Source object type passed to resolvers.
@typeParam — TContext - Context object type passed to resolvers.
The GraphQL name for this schema element.
name: string;Optionally provide a custom type resolver function. If one is not provided,
the default implementation will call isTypeOf on each implementing
Object type.
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[]>;Custom extensions
@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.
Serializes a runtime value as a scalar output value.
@typeParam — TExternal - The serialized representation returned for GraphQL results.
Parses a runtime input value as a scalar input value.
@typeParam — TInternal - The internal runtime representation produced from variable input.
Represents a range of characters represented by a lexical token within a Source.
export class Token {Creates a Token instance.
@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 }
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.
Note: is undefined for punctuation tokens, but typed as string for convenience in the parser.
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;Returns a JSON representation of this token.
@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 }
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.
Creates a Source instance.
@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 }
The GraphQL source text.
body: string;Name used in diagnostics for this source, such as a file path or request name.
name: string;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.
@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 }'
The character offset at which this Node begins.
readonly start: number;The character offset at which this Node ends.
readonly end: number;Returns a JSON representation of this location.
@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 }
The operation types supported by GraphQL executable definitions.
@category — Kinds
Takes a Source and a UTF-8 character offset, and returns the corresponding line and column as a SourceLocation.
@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 }
Render a helpful description of the location in the GraphQL Source document.
@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 | ^' }
Render a helpful description of the location in the GraphQL Source document.
@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 | ^'
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.
@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
The (1-indexed) line containing the current token.
line: number;Character offset where the current line starts.
lineStart: number;Advances the token stream to the next non-ignored token.
@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
Looks ahead and returns the next non-ignored token, but does not change the state of Lexer.
@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; // => ''
@category — Lexing
An exported enum describing the different kinds of tokens that the lexer emits.
Given a GraphQL source, parses it into a Document. Throws GraphQLError if a syntax error is encountered.
@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; // => undefineddirectiveDocument.definitions[0].kind; // => 'DirectiveDefinition'lexerDocument.definitions[0].kind; // => 'OperationDefinition'
Given a string containing a GraphQL value (ex. [42]), parse the AST for
that value.
Throws GraphQLError if a syntax error is encountered.
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'
Similar to parseValue(), but raises a parse error if it encounters a variable. The return type will be a constant value.
@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
Given a string containing a GraphQL Type (ex. [Int!]), parse the AST for
that type.
Throws GraphQLError if a syntax error is encountered.
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'
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.
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'
Converts an AST into a string, using one set of reasonable formatting rules.
@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}'
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.
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; // => leaveCountenterCount > 0; // => true
Traverses an AST with reducer callbacks and returns the reduced value.
@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 }'
A reducer is composed of reducer functions that convert AST nodes into another form.
@internal —
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.
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']
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.
@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
Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind.
@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
A value that can be returned from a visitor function to stop traversal.
export const BREAK: unknown = ...@category — Kinds
The set of allowed kind values for AST nodes.
AST kind for input object type definition nodes.
INPUT_OBJECT_TYPE_DEFINITION = "InputObjectTypeDefinition",AST kind for input object type extension nodes.
INPUT_OBJECT_TYPE_EXTENSION = "InputObjectTypeExtension",AST kind for directive argument coordinate nodes.
DIRECTIVE_ARGUMENT_COORDINATE = "DirectiveArgumentCoordinate"@category — Kinds
The set of allowed directive location values.
Directive location for input object field definitions.
INPUT_FIELD_DEFINITION = "INPUT_FIELD_DEFINITION",Directive location for directive definitions and extensions.
DIRECTIVE_DEFINITION = "DIRECTIVE_DEFINITION"Returns true when the AST node is a definition node.
@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
Returns true when the AST node is an executable definition node.
@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
Returns true when the AST node is a selection node.
@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
Returns true when the AST node is a value node.
@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
Returns true when the AST node is a constant value node.
@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
Returns true when the AST node is a type node.
@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
Returns true when the AST node is a type system definition node.
@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
Returns true when the AST node is a type definition node.
@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
Returns true when the AST node is a type system extension node.
@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
Returns true when the AST node is a type extension node.
@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
Returns true when the AST node is a schema coordinate node.
@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
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.
@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.
EXPERIMENTAL:
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
Internal parser hook for GraphQL.js entry points that need to parse a restricted grammar with an alternate lexer.
@internal —
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;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.
@deprecated — Will be removed in v17. In v17, use TokenKind as both the
runtime value and the type.
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.
@deprecated — Will be removed in v17. In v17, use Kind as both the runtime
value and the type.
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.
@deprecated — Will be removed in v17. In v17, use DirectiveLocation as both
the runtime value and the type.
A visitor defines the callbacks called during AST traversal.
export type ASTVisitor = EnterLeaveVisitor<ASTNode> | KindVisitorA visitor is composed of visit functions called for each node during traversal.
@typeParam — TVisitedNode - AST node type handled by this visitor function.
Deprecated visitor key map type retained for compatibility. Inline this mapped type at use sites because ASTVisitorKeyMap will be removed in v17.
@deprecated — Please inline it. Will be removed in v17
The list of all possible AST node types.
export type ASTNode = NameNode | DocumentNode | OperationDefinitionNode | VariableDefinitionNode | VariableNode | SelectionSetNode | FieldNode | ArgumentNode | FragmentSpreadNode | InlineFragmentNode | FragmentDefinitionNode | IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ListValueNode | ObjectValueNode | ObjectFieldNode | DirectiveNode | NamedTypeNode | ListTypeNode | NonNullTypeNode | SchemaDefinitionNode | OperationTypeDefinitionNode | ScalarTypeDefinitionNode | ObjectTypeDefinitionNode | FieldDefinitionNode | InputValueDefinitionNode | InterfaceTypeDefinitionNode | UnionTypeDefinitionNode | EnumTypeDefinitionNode | EnumValueDefinitionNode | InputObjectTypeDefinitionNode | DirectiveDefinitionNode | SchemaExtensionNode | ScalarTypeExtensionNode | ObjectTypeExtensionNode | InterfaceTypeExtensionNode | UnionTypeExtensionNode | EnumTypeExtensionNode | InputObjectTypeExtensionNode | DirectiveExtensionNode | TypeCoordinateNode | MemberCoordinateNode | ArgumentCoordinateNode | DirectiveCoordinateNode | DirectiveArgumentCoordinateNodeUtility type listing all nodes indexed by their kind.
export type ASTKindToNode = { }An identifier in a GraphQL document.
export interface NameNode {Parsed value represented by this node.
readonly value: string;The root AST node for a parsed GraphQL document.
export interface DocumentNode {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;Any top-level definition that may appear in a GraphQL document.
export type DefinitionNode = ExecutableDefinitionNode | TypeSystemDefinitionNode | TypeSystemExtensionNodeAny executable definition that may appear in an operation document.
export type ExecutableDefinitionNode = OperationDefinitionNode | FragmentDefinitionNodeA 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;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[];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;Directives available in this schema or applied to this AST node.
readonly directives?: readonly ConstDirectiveNode[];A variable reference, such as $id.
A set of fields and fragments selected from an object, interface, or union.
export interface SelectionSetNode { }Any selection that may appear inside a selection set.
export type SelectionNode = FieldNode | FragmentSpreadNode | InlineFragmentNodeA field selected in an executable GraphQL document.
export interface FieldNode {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[];An argument supplied to a field or directive.
export interface ArgumentNode { }An argument node whose value is guaranteed to be constant.
export interface ConstArgumentNode { }A named fragment spread, such as ...userFields.
The discriminator identifying the concrete AST or introspection kind.
readonly kind: FRAGMENT_SPREAD;Directives available in this schema or applied to this AST node.
readonly directives?: readonly DirectiveNode[];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;Directives available in this schema or applied to this AST node.
readonly directives?: readonly DirectiveNode[];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;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.
@deprecated — variableDefinitions will be removed in v17.0.0
Directives available in this schema or applied to this AST node.
readonly directives?: readonly DirectiveNode[];Any value literal that may appear in an executable GraphQL document.
export type ValueNode = VariableNode | IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ListValueNode | ObjectValueNodeAny value literal that is guaranteed not to contain a variable reference.
export type ConstValueNode = IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ConstListValueNode | ConstObjectValueNodeAn integer value literal.
export interface IntValueNode {Parsed value represented by this node.
readonly value: string;A floating-point value literal.
export interface FloatValueNode {Parsed value represented by this node.
readonly value: string;A string value literal.
export interface StringValueNode {Parsed value represented by this node.
readonly value: string;Whether this string was parsed from block string syntax.
readonly block?: boolean;A boolean value literal.
export interface BooleanValueNode {Parsed value represented by this node.
readonly value: boolean;An enum value literal.
export interface EnumValueNode {Parsed value represented by this node.
readonly value: string;A list value literal.
export interface ListValueNode {Values contained in this enum, list, or input-object definition.
readonly values: readonly ValueNode[];A list value literal whose elements are all constant values.
export interface ConstListValueNode {Values contained in this enum, list, or input-object definition.
readonly values: readonly ConstValueNode[];An input object value literal.
export interface ObjectValueNode {Fields declared by this object, interface, input object, or literal.
readonly fields: readonly ObjectFieldNode[];An input object value literal whose fields are all constant values.
export interface ConstObjectValueNode {Fields declared by this object, interface, input object, or literal.
readonly fields: readonly ConstObjectFieldNode[];A field inside an input object value literal.
export interface ObjectFieldNode { }A field inside a constant input object value literal.
export interface ConstObjectFieldNode { }A directive applied to an executable or type-system location.
export interface DirectiveNode {Arguments supplied to this field, directive, or coordinate.
readonly arguments?: readonly ArgumentNode[];A directive whose arguments are all constant values.
export interface ConstDirectiveNode {Arguments supplied to this field, directive, or coordinate.
readonly arguments?: readonly ConstArgumentNode[];Any GraphQL type reference AST node.
export type TypeNode = NamedTypeNode | ListTypeNode | NonNullTypeNodeA named type reference.
export interface NamedTypeNode { }A list type reference.
export interface ListTypeNode { }A non-null type reference.
export interface NonNullTypeNode {The GraphQL type reference or runtime type for this element.
readonly type: NamedTypeNode | ListTypeNode;Any type-system definition that may appear in a schema document.
export type TypeSystemDefinitionNode = SchemaDefinitionNode | TypeDefinitionNode | DirectiveDefinitionNodeA schema definition in a type-system document.
export interface SchemaDefinitionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: SCHEMA_DEFINITION;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[];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;Any named type definition that may appear in a schema document.
export type TypeDefinitionNode = ScalarTypeDefinitionNode | ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode | UnionTypeDefinitionNode | EnumTypeDefinitionNode | InputObjectTypeDefinitionNodeA 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 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[];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 optional GraphQL description associated with this definition.
readonly description?: StringValueNode;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[];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 optional GraphQL description associated with this definition.
readonly description?: StringValueNode;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[];An argument or input-field definition.
export interface InputValueDefinitionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: INPUT_VALUE_DEFINITION;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[];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 optional GraphQL description associated with this definition.
readonly description?: StringValueNode;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[];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 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[];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 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[];Values contained in this enum, list, or input-object definition.
readonly values?: readonly EnumValueDefinitionNode[];An enum value definition.
export interface EnumValueDefinitionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: ENUM_VALUE_DEFINITION;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[];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 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[];Fields declared by this object, interface, input object, or literal.
readonly fields?: readonly InputValueDefinitionNode[];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 optional GraphQL description associated with this definition.
readonly description?: StringValueNode;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;Any type-system extension that may appear in a schema extension document.
export type TypeSystemExtensionNode = SchemaExtensionNode | TypeExtensionNode | DirectiveExtensionNodeA schema extension in a type-system document.
export interface SchemaExtensionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: SCHEMA_EXTENSION;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[];Any named type extension that may appear in a schema extension document.
export type TypeExtensionNode = ScalarTypeExtensionNode | ObjectTypeExtensionNode | InterfaceTypeExtensionNode | UnionTypeExtensionNode | EnumTypeExtensionNode | InputObjectTypeExtensionNodeA scalar type extension.
export interface ScalarTypeExtensionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: SCALAR_TYPE_EXTENSION;Directives available in this schema or applied to this AST node.
readonly directives?: readonly ConstDirectiveNode[];An object type extension.
export interface ObjectTypeExtensionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: OBJECT_TYPE_EXTENSION;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[];An interface type extension.
export interface InterfaceTypeExtensionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: INTERFACE_TYPE_EXTENSION;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[];A union type extension.
export interface UnionTypeExtensionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: UNION_TYPE_EXTENSION;Directives available in this schema or applied to this AST node.
readonly directives?: readonly ConstDirectiveNode[];An enum type extension.
export interface EnumTypeExtensionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: ENUM_TYPE_EXTENSION;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[];An input object type extension.
export interface InputObjectTypeExtensionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: INPUT_OBJECT_TYPE_EXTENSION;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[];A directive extension.
export interface DirectiveExtensionNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: DIRECTIVE_EXTENSION;Directives available in this schema or applied to this AST node.
readonly directives?: readonly ConstDirectiveNode[];Any AST node representing a GraphQL schema coordinate.
export type SchemaCoordinateNode = TypeCoordinateNode | MemberCoordinateNode | ArgumentCoordinateNode | DirectiveCoordinateNode | DirectiveArgumentCoordinateNodeA schema coordinate that refers to a named type.
export interface TypeCoordinateNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: TYPE_COORDINATE;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;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;A schema coordinate that refers to a directive.
export interface DirectiveCoordinateNode {The discriminator identifying the concrete AST or introspection kind.
readonly kind: DIRECTIVE_COORDINATE;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;Implements the "Executing requests" section of the GraphQL specification.
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; // => 2result.errors[1].message; // matches /error limit reached/
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.
@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
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:
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.
Given a Path, return an Array of the path keys.
@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); // => []
Prepares an object map of argument values given a list of argument definitions and list of argument AST nodes.
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
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.
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; // => 2result.errors[1].message; // matches /error limit reached/
Options used when coercing variable values before execution.
@internal —
Maximum number of variable coercion errors before coercion stops.
@internal —
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.
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
AST node shape accepted by getDirectiveValues.
@internal —
Directives attached to the AST node.
@internal —
Implements the "Subscribe" algorithm described in the GraphQL specification.
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.'
Implements the "CreateSourceEventStream" algorithm described in the GraphQL specification, resolving the subscription source event stream.
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
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.
@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.
Arguments accepted by execute and executeSync.
export interface ExecutionArgs {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<{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;Represents the response produced by executing a GraphQL operation.
@typeParam — TData - Shape of the execution data payload.
@typeParam — TExtensions - Shape of the extensions payload.
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;A JSON-serializable GraphQL execution result.
@typeParam — TData - Shape of the formatted data payload.
@typeParam — TExtensions - Shape of the formatted extensions payload.
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.
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
Implements the "Validation" section of the spec.
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; // => 2errors[1].message; // => 'Too many validation errors, error limit reached. Validation aborted.'
Options used when validating a GraphQL document.
@internal —
Maximum number of validation errors before validation stops.
@internal —
Validation context passed to query validation rules.
export class ValidationContext extends ASTValidationContext {Creates a ValidationContext instance.
@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.'
Returns the schema being used by this validation context.
@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'
Returns variable usages found directly within this node.
@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'
Returns variable usages for an operation, including variables used by referenced fragments.
@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']
Returns the current output type at this point in traversal.
@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'
Returns the current parent composite type.
@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'
Returns the current input type at this point in traversal.
@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'
Returns the parent input type for the current input position.
@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'
Returns the current field definition.
@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'
Returns the current directive definition.
@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'
Returns the current argument definition.
@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'
Returns the current enum value definition.
@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'
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.
@internal —
This set includes all validation rules defined by the GraphQL spec.
The order of the rules in this list has been adjusted to lead to the most clear output when encountering multiple validation errors.
Technically these aren't part of the spec but they are strongly encouraged validation rules.
export const recommendedRules: readonly typeof MaxIntrospectionDepthRule[] = ...Executable definitions
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; // => []
Fields on correct type
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; // => []
Fragments on composite type
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; // => []
Known argument names
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; // => []
Known directives
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; // => []
@internal —
class SDLValidationContext extends ASTValidationContext {Known fragment names
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; // => []
Known type names
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; // => []
Lone anonymous operation
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; // => []
No fragment cycles
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; // => []
No undefined variables
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; // => []
No unused fragments
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; // => []
No unused variables
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; // => []
Overlapping fields can be merged
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; // => []
Possible fragment spread
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; // => []
Provided required arguments
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; // => []
Scalar leafs
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; // => []
Subscriptions must only include a non-introspection field.
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; // => []
Unique argument names
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; // => []
Unique directive names per location
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; // => []
Unique fragment names
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; // => []
Unique input field names
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; // => []
Unique operation names
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; // => []
Unique variable names
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; // => []
Value literals of correct type
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; // => []
Variables are input types
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; // => []
Variables in allowed position
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; // => []
Implements the max introspection depth validation rule.
@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; // => []
Lone Schema definition
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
Unique operation types
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
Unique type names
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
Unique enum value names
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
Unique field definition names
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
Unique argument definition names
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
Unique directive names
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
Possible type extension
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
No deprecated
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; // => []
Prohibit introspection queries
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; // => []
A function that creates an AST visitor for validating a GraphQL document.
export type ValidationRule = (context: ValidationContext) => ASTVisitorA 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.
@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
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.
@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.
An array of { line, column } locations within the source GraphQL document
which correspond to this error.
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().
An array describing the JSON-path into the execution response which corresponds to this error. Only included for errors during execution.
Enumerable, and appears in the result of JSON.stringify().
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.
Note that if this Error represents more than one node, the source may not represent nodes after the first node.
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;Returns this error as a human-readable message with source locations.
@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 | ^'
Returns the JSON representation used when this object is serialized.
@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' } }
Produces a GraphQLError representing a syntax error, containing useful descriptive information about the syntax error's position in the source.
@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 }]
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.
@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']
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.
@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
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.
@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
Options used to construct a GraphQLError.
export interface GraphQLErrorOptions {Character offsets in the source document associated with this error.
positions?: Maybe<readonly number[]>;Original error that caused this GraphQLError, if one exists.
originalError?: Maybe<Error & {Extension fields associated with this value.
readonly extensions?: unknown;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.
Reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.
readonly extensions?: GraphQLFormattedErrorExtensions;Custom extensions
@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.
Custom formatted extensions
@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.
Produce the GraphQL query recommended for a full schema introspection. Accepts optional IntrospectionOptions.
@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
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.
@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
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.
@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
Build an IntrospectionQuery from a GraphQLSchema
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; // => undefinedurlType.description; // => undefinedintrospection.__schema.description; // => undefineddeprecatedDirective.isRepeatable; // => undefined
Build a GraphQLSchema for use by client tools.
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'
Builds a GraphQLSchema from a parsed schema definition language document.
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 errorbuildASTSchema(document, {assumeValid: true,assumeValidSDL: true,}); // does not throw
Builds a GraphQLSchema directly from a schema definition language source.
@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
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.
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 errorextendSchema(schema, invalidExtension, {assumeValid: true,assumeValidSDL: true,}); // does not throw
Set to true to assume the SDL is valid.
Default: false
Sort GraphQLSchema.
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 // }
Prints the schema.
@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')
Prints the type.
@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')
Prints the introspection schema.
@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/
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.
@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
Resolves a list type AST node against a schema.
@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
Resolves a non-null type AST node against a schema.
@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!]!'
Resolves a type AST node against a schema.
@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
Produces a JavaScript value given a GraphQL Value AST.
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 Value | JSON Value |
|---|---|
| Input Object | Object |
| List | Array |
| Boolean | Boolean |
| String | String |
| Int / Float | Number |
| Enum Value | Unknown |
| NullValue | null |
@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 }); // => 5valueFromAST(parseValue('$stars'), GraphQLInt, {}); // => undefined
Produces a JavaScript value given a GraphQL Value AST.
Because no GraphQL type is provided, the returned JavaScript value reflects the provided GraphQL value AST.
| GraphQL Value | JavaScript Value |
|---|---|
| Input Object | Object |
| List | Array |
| Boolean | Boolean |
| String / Enum | String |
| Int / Float | Number |
| Null | null |
@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'
Produces a GraphQL Value AST given a JavaScript object. Function will match JavaScript/JSON values to GraphQL AST schema format by using suggested GraphQLInputType.
A GraphQL type must be provided, which will be used to interpret different JavaScript values.
| JSON Value | GraphQL Value |
|---|---|
| Object | Input Object |
| Array | List |
| Boolean | Boolean |
| String | String / Enum Value |
| Number | Int / Float |
| Unknown | Enum Value |
| null | NullValue |
@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
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).
Creates a TypeInfo instance.
@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'
Returns the current output type at this point in traversal.
@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' }
Returns the current parent composite type.
@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' }
Returns the current input type at this point in traversal.
@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' }
Returns the parent input type for the current input position.
@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' }
Returns the current field definition.
@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'
Returns the default value for the current input position.
@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
Returns the current directive definition.
@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'
Returns the current argument definition.
@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'
Returns the current enum value definition.
@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'
Updates this TypeInfo instance for an entered AST node.
@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'
Updates this TypeInfo instance for a left AST node.
@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
Creates a new visitor instance which maintains a provided TypeInfo instance along with visiting visitor.
@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' }]
Coerces a JavaScript value given a GraphQL Input Type.
@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; // => undefinederrors; // => [ { path: [], invalidValue: null, message: 'Expected non-nullable type "Int!" not to be null.' } ]
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.
@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
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.
@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/
Strips characters that are not significant to the validity or execution of a GraphQL document:
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}'
Provided two types, return true if the types are equal (invariant).
@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
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).
@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
Provided two composite types, determine if they "overlap". Two composite types overlap when the Sets of possible concrete types for each intersect.
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
Upholds the spec rules about naming. This deprecated helper is retained for
backwards compatibility; call assertName instead because assertValidName
will be removed in v17.
@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
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.
@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
Categories of schema changes that may break existing operations.
export enum BreakingChangeType {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 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"Categories of schema changes that may be dangerous for existing operations.
export enum DangerousChangeType {Dangerous change code for optional input field added.
OPTIONAL_INPUT_FIELD_ADDED = "OPTIONAL_INPUT_FIELD_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"Given two schemas, returns an Array containing descriptions of all the types of breaking changes covered by the other functions down below.
@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/
Given two schemas, returns an Array containing descriptions of all the types of potentially dangerous changes covered by the other functions down below.
@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/
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.
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
Resolves schema coordinate from a parsed SchemaCoordinate node.
@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'
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
Whether to include isRepeatable flag on directives.
Default: false
Whether to include description field on schema.
Default: false
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
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.
Default: 9
The result shape returned by a full introspection query.
export interface IntrospectionQuery { }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>>;Directives available in this schema or applied to this AST node.
readonly directives: readonly IntrospectionDirective[];Any introspection representation of a GraphQL type.
export type IntrospectionType = IntrospectionScalarType | IntrospectionObjectType | IntrospectionInterfaceType | IntrospectionUnionType | IntrospectionEnumType | IntrospectionInputObjectTypeAn introspection type that can appear in input position.
export type IntrospectionInputType = IntrospectionScalarType | IntrospectionEnumType | IntrospectionInputObjectTypeAn introspection type that can appear in output position.
export type IntrospectionOutputType = IntrospectionScalarType | IntrospectionObjectType | IntrospectionInterfaceType | IntrospectionUnionType | IntrospectionEnumTypeThe 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>;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>[];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>[];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>[];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>;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;Any introspection representation of a type reference.
export type IntrospectionTypeRef = IntrospectionNamedTypeRef | IntrospectionListTypeRef | IntrospectionNonNullTypeRef<IntrospectionNamedTypeRef | IntrospectionListTypeRef>An introspection type reference that can appear in input position.
export type IntrospectionInputTypeRef = IntrospectionNamedTypeRef<IntrospectionInputType> | IntrospectionListTypeRef<IntrospectionInputTypeRef> | IntrospectionNonNullTypeRef<IntrospectionNamedTypeRef<IntrospectionInputType> | IntrospectionListTypeRef<IntrospectionInputTypeRef>>An introspection type reference that can appear in output position.
export type IntrospectionOutputTypeRef = IntrospectionNamedTypeRef<IntrospectionOutputType> | IntrospectionListTypeRef<IntrospectionOutputTypeRef> | IntrospectionNonNullTypeRef<IntrospectionNamedTypeRef<IntrospectionOutputType> | IntrospectionListTypeRef<IntrospectionOutputTypeRef>>The introspection representation of a named type reference.
@typeParam — T - The introspection type represented by this named type reference.
The introspection kind discriminator for this type reference or type.
readonly kind: T["kind"];The GraphQL name for this schema element.
readonly name: string;The introspection representation of a list type reference.
@typeParam — T - The introspection type reference wrapped by this list type reference.
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;The introspection representation of a non-null type reference.
@typeParam — T - The introspection type reference wrapped by this non-null type reference.
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;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>;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;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;Whether this field, argument, enum value, or input value is deprecated.
readonly isDeprecated?: boolean;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;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;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.
Default: false
Description of a schema change that may break existing operations.
export interface BreakingChange {Human-readable description of the breaking schema change.
description: string;Description of a schema change that may be dangerous for existing operations.
export interface DangerousChange {Human-readable description of the dangerous schema change.
description: string;Wrapper type that contains DocumentNode and types that can be deduced from it.
@typeParam — TResponseData - Typed GraphQL response data shape.
@typeParam — TRequestVariables - Typed GraphQL request variables shape.
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 | ResolvedDirectiveArgumentA resolved schema element may be one of the following kinds:
@internal —
@internal —
interface ResolvedField {@internal —
interface ResolvedInputField {@internal —
interface ResolvedEnumValue {@internal —
interface ResolvedFieldArgument {@internal —
interface ResolvedDirective {@internal —
interface ResolvedDirectiveArgument {