🎉 Explore GraphQLConf 2026 • May 19-21 • Fremont, CA • View the schedule
v17 APIgraphql/utilities

Utilities for building schemas, working with introspection, transforming ASTs, and comparing GraphQL types.

These exports are also available from the root graphql package.

For documentation purposes, these exports are grouped into the following categories:

Category: Type Info

Classes:
TypeInfo

Functions:
visitWithTypeInfo()

Classes

TypeInfo

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).


Constructor

Creates a TypeInfo instance.

Signature:

new TypeInfo(
  schema: GraphQLSchema,
  initialType?: Maybe<GraphQLType>,
  fragmentSignatures?: Maybe<
    (
      fragmentName: string,
    ) => Maybe<FragmentSignature>
  >,
);

Arguments
NameTypeDescription
schemaGraphQLSchemaSchema used for type lookups.
initialType?Maybe<GraphQLType>Optional type to use at the start of traversal.
fragmentSignatures?Maybe< (fragmentName: string) => Maybe<FragmentSignature> >Fragment signatures available during traversal.
getType()

Returns the current output type at this point in traversal.

Signature:

getType(): Maybe<GraphQLOutputType>;

Returns
TypeDescription
Maybe<GraphQLOutputType>The current output type, if known.

Example
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' }

getParentType()

Returns the current parent composite type.

Signature:

getParentType(): Maybe<GraphQLCompositeType>;

Returns
TypeDescription
Maybe<GraphQLCompositeType>The current parent composite type, if known.

Example
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' }

getInputType()

Returns the current input type at this point in traversal.

Signature:

getInputType(): Maybe<GraphQLInputType>;

Returns
TypeDescription
Maybe<GraphQLInputType>The current input type, if known.

Example
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' }

getParentInputType()

Returns the parent input type for the current input position.

Signature:

getParentInputType(): Maybe<GraphQLInputType>;

Returns
TypeDescription
Maybe<GraphQLInputType>The parent input type, if known.

Example
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' }

getFieldDef()

Returns the current field definition.

Signature:

getFieldDef(): Maybe<
  GraphQLField<unknown, unknown>
>;

Returns
TypeDescription
Maybe<GraphQLField<unknown, unknown>>The current field definition, if known.

Example
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'

getDefaultValue()

Returns the default input representation for the current input position.

Signature:

getDefaultValue(): unknown;

Returns
TypeDescription
unknownThe current default input, if one is available.

Example
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; // => { literal: { kind: 'IntValue', value: '10' } }

getDirective()

Returns the current directive definition.

Signature:

getDirective(): Maybe<GraphQLDirective>;

Returns
TypeDescription
Maybe<GraphQLDirective>The current directive definition, if known.

Example
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'

getArgument()

Returns the current argument definition.

Signature:

getArgument(): Maybe<GraphQLArgument>;

Returns
TypeDescription
Maybe<GraphQLArgument>The current argument definition, if known.

Example
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'

getFragmentSignature()

Returns the current fragment signature.

Signature:

getFragmentSignature(): Maybe<FragmentSignature>;

Returns
TypeDescription
Maybe<FragmentSignature>The fragment signature for the current fragment definition.

Example
import { parse, visit } from 'graphql/language';
import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';
 
const schema = buildSchema(`
  type Query {
    greeting: String
  }
`);
const document = parse(
  `
    {
      ...GreetingFields
    }
 
    fragment GreetingFields on Query {
      greeting
    }
  `,
  { experimentalFragmentArguments: true },
);
const typeInfo = new TypeInfo(schema);
let fragmentName;
 
visit(
  document,
  visitWithTypeInfo(typeInfo, {
    FragmentSpread: () => {
      fragmentName = typeInfo.getFragmentSignature()?.definition.name.value;
    },
  }),
);
 
fragmentName; // => 'GreetingFields'

getFragmentSignatureByName()

Returns the function used to look up fragment signatures by name.

Signature:

getFragmentSignatureByName(): (
  fragmentName: string,
) => Maybe<FragmentSignature>;

Returns
TypeDescription
( fragmentName: string, ) => Maybe<FragmentSignature>A function that maps fragment names to fragment signatures.

Example
import { parse, visit } from 'graphql/language';
import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';
 
const schema = buildSchema(`
  type Query {
    greeting: String
  }
`);
const document = parse(
  `
    {
      ...GreetingFields
    }
 
    fragment GreetingFields on Query {
      greeting
    }
  `,
  { experimentalFragmentArguments: true },
);
const typeInfo = new TypeInfo(schema);
let fragmentName;
 
visit(
  document,
  visitWithTypeInfo(typeInfo, {
    Document: () => {
      const getFragmentSignature = typeInfo.getFragmentSignatureByName();
      fragmentName =
        getFragmentSignature('GreetingFields')?.definition.name.value;
    },
  }),
);
 
fragmentName; // => 'GreetingFields'

getFragmentArgument()

Returns the current fragment argument definition.

Signature:

getFragmentArgument(): Maybe<VariableDefinitionNode>;

Returns
TypeDescription
Maybe<VariableDefinitionNode>The variable definition for the current fragment argument.

Example
import { parse, visit } from 'graphql/language';
import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';
 
const schema = buildSchema(`
  type Query {
    greeting(name: String): String
  }
`);
const document = parse(
  `
    {
      ...GreetingFields(name: "Ada")
    }
 
    fragment GreetingFields($name: String) on Query {
      greeting(name: $name)
    }
  `,
  { experimentalFragmentArguments: true },
);
const typeInfo = new TypeInfo(schema);
let argumentName;
 
visit(
  document,
  visitWithTypeInfo(typeInfo, {
    FragmentArgument: () => {
      argumentName = typeInfo.getFragmentArgument()?.variable.name.value;
    },
  }),
);
 
argumentName; // => 'name'

getEnumValue()

Returns the current enum value definition.

Signature:

getEnumValue(): Maybe<GraphQLEnumValue>;

Returns
TypeDescription
Maybe<GraphQLEnumValue>The current enum value definition, if known.

Example
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'

enter()

Updates this TypeInfo instance for an entered AST node.

Signature:

enter(node: ASTNode): void;

Arguments
NameTypeDescription
nodeASTNodeAST node being entered.

Example
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'

leave()

Updates this TypeInfo instance for a left AST node.

Signature:

leave(node: ASTNode): void;

Arguments
NameTypeDescription
nodeASTNodeAST node being entered.

Example
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

Functions

visitWithTypeInfo()

Creates a new visitor instance which maintains a provided TypeInfo instance along with visiting visitor.

Signature:

visitWithTypeInfo(
  typeInfo: TypeInfo,
  visitor: ASTVisitor,
): ASTVisitor;

Arguments
NameTypeDescription
typeInfoTypeInfoTypeInfo instance to update during traversal.
visitorASTVisitorVisitor callbacks to wrap with TypeInfo updates.

Returns
TypeDescription
ASTVisitorA visitor that keeps TypeInfo in sync while delegating callbacks.

Example
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' }]

Category: Values

Functions

astFromValue() Deprecated

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.

This deprecated function will be removed in v18. Use valueToLiteral() instead, and take care to operate on external values.

JSON ValueGraphQL Value
ObjectInput Object
ArrayList
BooleanBoolean
StringString / Enum Value
NumberInt / Float
BigIntInt
UnknownEnum Value
nullNullValue

Signature:

astFromValue(
  value: unknown,
  type: GraphQLInputType,
): Maybe<ConstValueNode>;

Arguments
NameTypeDescription
valueunknownRuntime value to convert.
typeGraphQLInputTypeThe GraphQL type to inspect.

Returns
TypeDescription
Maybe<ConstValueNode>A GraphQL value AST for the provided JavaScript value, or null when no literal can represent it.

Example
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

coerceInputValue()

Coerces a JavaScript value given a GraphQL Input Type.

Returns undefined when the value could not be validly coerced according to the provided type. Use validateInputValue when coercion diagnostics are needed.

Signature:

coerceInputValue(
  inputValue: unknown,
  type: GraphQLInputType,
): unknown;

Arguments
NameTypeDescription
inputValueunknownJavaScript value to coerce.
typeGraphQLInputTypeGraphQL input type to coerce the value against.

Returns
TypeDescription
unknownCoerced value, or undefined if coercion fails.

Example
// Coerce runtime input values, returning undefined when coercion fails.
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); // => undefined

coerceInputLiteral()

Produces a coerced “internal” JavaScript value given a GraphQL Value AST.

Returns undefined when the value could not be validly coerced according to the provided type.

Signature:

coerceInputLiteral(
  valueNode: ValueNode,
  type: GraphQLInputType,
  variableValues?: Maybe<VariableValues>,
  fragmentVariableValues?: Maybe<FragmentVariableValues>,
): unknown;

Arguments
NameTypeDescription
valueNodeValueNodeGraphQL value AST node to coerce.
typeGraphQLInputTypeGraphQL input type to coerce the literal against.
variableValues?Maybe<VariableValues>Operation variable values returned by getVariableValues.
fragmentVariableValues?Maybe<FragmentVariableValues>Fragment variable values for the current fragment scope.

Returns
TypeDescription
unknownCoerced value, or undefined if coercion fails.

Example 1
// Coerce literal input values without variables.
import { parseValue } from 'graphql/language';
import {
  GraphQLInputObjectType,
  GraphQLInt,
  GraphQLNonNull,
  GraphQLString,
} from 'graphql/type';
import { coerceInputLiteral } from 'graphql/utilities';
 
const ReviewInput = new GraphQLInputObjectType({
  name: 'ReviewInput',
  fields: {
    stars: { type: new GraphQLNonNull(GraphQLInt) },
    comment: { type: GraphQLString },
  },
});
 
coerceInputLiteral(parseValue('{ stars: 5, comment: "Loved it" }'), ReviewInput); // => { stars: 5, comment: 'Loved it' }
coerceInputLiteral(parseValue('{ comment: "Missing" }'), ReviewInput); // => undefined

Example 2
// This variant resolves variable references using VariableValues from getVariableValues().
import assert from 'node:assert';
import { parse, parseValue } from 'graphql/language';
import { GraphQLInt } from 'graphql/type';
import { getVariableValues } from 'graphql/execution';
import { buildSchema, coerceInputLiteral } from 'graphql/utilities';
 
const schema = buildSchema(`
  type Query {
    review(stars: Int): String
  }
`);
const document = parse('query ($stars: Int = 5) { review(stars: $stars) }');
const operation = document.definitions[0];
const result = getVariableValues(
  schema,
  operation.variableDefinitions,
  { stars: '4' },
);
 
assert('variableValues' in result);
 
coerceInputLiteral(parseValue('$stars'), GraphQLInt, result.variableValues); // => 4

replaceVariables()

Replaces any Variables found within an AST Value literal with literals supplied from a map of variable values, or removed if no variable replacement exists, returning a constant value.

Used primarily to ensure only complete constant values are used during input coercion of custom scalars which accept complex literals.

Signature:

replaceVariables(
  valueNode: ValueNode,
  variableValues?: Maybe<VariableValues>,
  fragmentVariableValues?: Maybe<FragmentVariableValues>,
): ConstValueNode;

Arguments
NameTypeDescription
valueNodeValueNodeValue AST node in which variables should be replaced.
variableValues?Maybe<VariableValues>Operation variable values returned by getVariableValues.
fragmentVariableValues?Maybe<FragmentVariableValues>Fragment variable values for the current fragment scope.

Returns
TypeDescription
ConstValueNodeA constant value AST with variables replaced.

Example
import assert from 'node:assert';
import { parse, parseValue, print } from 'graphql/language';
import { getVariableValues } from 'graphql/execution';
import { buildSchema, replaceVariables } from 'graphql/utilities';
 
const schema = buildSchema(`
  type Query {
    review(stars: Int = 5): String
  }
`);
const document = parse(
  'query ($stars: Int = 5) { review(stars: $stars) }',
);
const operation = document.definitions[0];
const result = getVariableValues(
  schema,
  operation.variableDefinitions,
  { stars: 4 },
);
 
assert('variableValues' in result);
 
const literal = replaceVariables(
  parseValue('{ stars: $stars, comment: $missing }'),
  result.variableValues,
);
 
print(literal); // => '{ stars: 4 }'

validateInputValue()

Validate that the provided input value is allowed for this type, collecting all errors via a callback function.

Signature:

validateInputValue(
  inputValue: unknown,
  type: GraphQLInputType,
  onError: (
    error: GraphQLError,
    path: readonly (string | number)[],
  ) => void,
  hideSuggestions?: Maybe<boolean>,
): void;

Arguments
NameTypeDescription
inputValueunknownJavaScript value to validate.
typeGraphQLInputTypeGraphQL input type to validate the value against.
onError( error: GraphQLError, path: readonly (string | number)[], ) => voidCallback invoked for each validation error and path.
hideSuggestions?Maybe<boolean>Whether suggestion text should be omitted from errors.

Example 1
// Collect validation errors with their input paths.
import {
  GraphQLInputObjectType,
  GraphQLInt,
  GraphQLNonNull,
} from 'graphql/type';
import { validateInputValue } from 'graphql/utilities';
 
const ReviewInput = new GraphQLInputObjectType({
  name: 'ReviewInput',
  fields: {
    stars: { type: new GraphQLNonNull(GraphQLInt) },
  },
});
const errors = [];
 
validateInputValue({ stars: 'bad' }, ReviewInput, (error, path) => {
  errors.push({ message: error.message, path });
});
 
errors; // => [ { message: 'Expected value of type "Int", found: "bad".', path: ['stars'] } ]

Example 2
// This variant hides suggestion text for unknown input fields.
import { GraphQLInputObjectType, GraphQLString } from 'graphql/type';
import { validateInputValue } from 'graphql/utilities';
 
const ReviewInput = new GraphQLInputObjectType({
  name: 'ReviewInput',
  fields: {
    comment: { type: GraphQLString },
  },
});
const errors = [];
 
validateInputValue(
  { rating: 'extra field' },
  ReviewInput,
  (error) => {
    errors.push(error.message);
  },
  true,
);
 
errors; // => ['Expected value of type "ReviewInput" not to include unknown field "rating", found: { rating: "extra field" }.']

validateInputLiteral()

Validate that the provided input literal is allowed for this type, collecting all errors via a callback function.

If variable values are not provided, the literal is validated statically (not assuming that those variables are missing runtime values).

Signature:

validateInputLiteral(
  valueNode: ValueNode,
  type: GraphQLInputType,
  onError: (
    error: GraphQLError,
    path: readonly (string | number)[],
  ) => void,
  variables?: Maybe<VariableValues>,
  fragmentVariableValues?: Maybe<FragmentVariableValues>,
  hideSuggestions?: Maybe<boolean>,
): void;

Arguments
NameTypeDescription
valueNodeValueNodeGraphQL value AST node to validate.
typeGraphQLInputTypeGraphQL input type to validate the literal against.
onError( error: GraphQLError, path: readonly (string | number)[], ) => voidCallback invoked for each validation error and path.
variables?Maybe<VariableValues>Operation variable values returned by getVariableValues.
fragmentVariableValues?Maybe<FragmentVariableValues>Fragment variable values for the current fragment scope.
hideSuggestions?Maybe<boolean>Whether suggestion text should be omitted from errors.

Example 1
// Validate literal input values and collect literal paths.
import { parseValue } from 'graphql/language';
import {
  GraphQLInputObjectType,
  GraphQLInt,
  GraphQLNonNull,
} from 'graphql/type';
import { validateInputLiteral } from 'graphql/utilities';
 
const ReviewInput = new GraphQLInputObjectType({
  name: 'ReviewInput',
  fields: {
    stars: { type: new GraphQLNonNull(GraphQLInt) },
  },
});
const errors = [];
 
validateInputLiteral(parseValue('{ stars: "bad" }'), ReviewInput, (error, path) => {
  errors.push({ message: error.message, path });
});
 
errors; // => [ { message: 'Expected value of type "Int", found: "bad".', path: ['stars'] } ]

Example 2
// This variant resolves variable references using VariableValues from getVariableValues().
import assert from 'node:assert';
import { parse, parseValue } from 'graphql/language';
import { GraphQLInt } from 'graphql/type';
import { getVariableValues } from 'graphql/execution';
import { buildSchema, validateInputLiteral } from 'graphql/utilities';
 
const schema = buildSchema(`
  type Query {
    review(stars: Int): String
  }
`);
const document = parse('query ($stars: Int = 5) { review(stars: $stars) }');
const operation = document.definitions[0];
const result = getVariableValues(
  schema,
  operation.variableDefinitions,
  { stars: '4' },
);
 
assert('variableValues' in result);
 
const errors = [];
validateInputLiteral(
  parseValue('$stars'),
  GraphQLInt,
  (error) => errors.push(error.message),
  result.variableValues,
  undefined,
  true,
);
 
errors; // => []

valueFromAST() Deprecated

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.

This deprecated function will be removed in v18. Use coerceInputLiteral() instead.

GraphQL ValueJSON Value
Input ObjectObject
ListArray
BooleanBoolean
StringString
Int / FloatNumber
Enum ValueUnknown
NullValuenull

Signature:

valueFromAST(
  valueNode: Maybe<ValueNode>,
  type: GraphQLInputType,
  variables?: Maybe<ObjMap<unknown>>,
): unknown;

Arguments
NameTypeDescription
valueNodeMaybe<ValueNode>GraphQL value AST node to convert.
typeGraphQLInputTypeThe GraphQL type to inspect.
variables?Maybe<ObjMap<unknown>>Optional runtime variable values keyed by variable name.

Returns
TypeDescription
unknownThe coerced JavaScript value, or undefined if the AST value cannot be coerced to the type.

Example 1
// 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 2
// This variant resolves variable references from runtime values.
import { parseValue } from 'graphql/language';
import { GraphQLInt } from 'graphql/type';
import { valueFromAST } from 'graphql/utilities';
 
valueFromAST(parseValue('$stars'), GraphQLInt, { stars: 5 }); // => 5
valueFromAST(parseValue('$stars'), GraphQLInt, {}); // => undefined

valueFromASTUntyped()

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 ValueJavaScript Value
Input ObjectObject
ListArray
BooleanBoolean
String / EnumString
Int / FloatNumber
Nullnull

Signature:

valueFromASTUntyped(
  valueNode: ValueNode,
  variables?: Maybe<ObjMap<unknown>>,
): unknown;

Arguments
NameTypeDescription
valueNodeValueNodeGraphQL value AST node to convert.
variables?Maybe<ObjMap<unknown>>Optional runtime variable values keyed by variable name.

Returns
TypeDescription
unknownJavaScript value represented by the GraphQL value AST.

Example
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'

valueToLiteral()

Produces a GraphQL Value AST given a JavaScript value and a GraphQL type.

Scalar types are converted by calling the valueToLiteral method on that type, otherwise the default scalar valueToLiteral method is used, defined below.

Provided value is a non-coerced “input” value. This function does not perform any coercion, however it does perform validation. Provided values which are invalid for the given type will result in an undefined return value.

Signature:

valueToLiteral(
  value: unknown,
  type: GraphQLInputType,
): ConstValueNode | undefined;

Arguments
NameTypeDescription
valueunknownJavaScript value to convert.
typeGraphQLInputTypeGraphQL input type to convert the value against.

Returns
TypeDescription
ConstValueNode | undefinedA GraphQL value AST, or undefined if the value is invalid.

Example
import { print } from 'graphql/language';
import {
  GraphQLInputObjectType,
  GraphQLInt,
  GraphQLList,
  GraphQLNonNull,
  GraphQLString,
} from 'graphql/type';
import { valueToLiteral } from 'graphql/utilities';
 
const ReviewInput = new GraphQLInputObjectType({
  name: 'ReviewInput',
  fields: {
    stars: { type: new GraphQLNonNull(GraphQLInt) },
    tags: { type: new GraphQLList(GraphQLString) },
  },
});
 
const literal = valueToLiteral({ stars: 5, tags: ['featured'] }, ReviewInput);
 
print(literal); // => '{ stars: 5, tags: ["featured"] }'
valueToLiteral({ tags: ['missing stars'] }, ReviewInput); // => undefined

Category: Schema Construction

Functions

buildASTSchema()

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.

Signature:

buildASTSchema(
  documentAST: DocumentNode,
  options?: BuildSchemaOptions,
): GraphQLSchema;

Arguments
NameTypeDescription
documentASTDocumentNodeThe parsed GraphQL document AST.
options?BuildSchemaOptionsOptional configuration for this operation.

Returns
TypeDescription
GraphQLSchemaThe schema built from the provided SDL document.

Example 1
// 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 2
// This variant uses validation options when the SDL references unknown types.
import { parse } from 'graphql/language';
import { buildASTSchema } from 'graphql/utilities';
 
const document = parse('type Query { broken: MissingType }');
 
buildASTSchema(document); // throws an error
buildASTSchema(document, {
  assumeValid: true,
  assumeValidSDL: true,
}); // does not throw

buildSchema()

Builds a GraphQLSchema directly from a schema definition language source.

Signature:

buildSchema(
  source: string | Source,
  options?: BuildSchemaOptions & ParseOptions,
): GraphQLSchema;

Arguments
NameTypeDescription
sourcestring | SourceThe GraphQL source text or source object.
options?BuildSchemaOptions & ParseOptionsOptional configuration for this operation.

Returns
TypeDescription
GraphQLSchemaThe schema built from the provided SDL document.

Example 1
// 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 2
// 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,
    experimentalFragmentArguments: true,
    noLocation: true,
  },
);
 
const directive = schema.getDirective('compose');
 
directive.name; // => 'compose'
directive.astNode.loc; // => undefined

extendSchema()

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.

Signature:

extendSchema(
  schema: GraphQLSchema,
  documentAST: DocumentNode,
  options?: { assumeValidSDL?: boolean | undefined },
): GraphQLSchema;

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.
documentASTDocumentNodeThe parsed GraphQL document AST.
options?{ assumeValidSDL?: boolean | undefined }Optional configuration for this operation.

Returns
TypeDescription
GraphQLSchemaA new schema with the extensions and definitions applied.

Example 1
// 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 2
// This variant bypasses validation for an otherwise invalid extension.
import { parse } from 'graphql/language';
import { buildSchema, extendSchema } from 'graphql/utilities';
 
const schema = buildSchema(`
  type Query {
    greeting: String
  }
`);
const invalidExtension = parse(`
  extend type Missing {
    field: String
  }
`);
 
extendSchema(schema, invalidExtension); // throws an error
extendSchema(schema, invalidExtension, {
    assumeValid: true,
    assumeValidSDL: true,
  }); // does not throw

lexicographicSortSchema()

Sort GraphQLSchema.

This function returns a sorted copy of the given GraphQLSchema.

Signature:

lexicographicSortSchema(
  schema: GraphQLSchema,
): GraphQLSchema;

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.

Returns
TypeDescription
GraphQLSchemaA copy of the schema with types, fields, arguments, and values sorted lexicographically.

Example
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
// }

Types

BuildSchemaOptions

Interface. Options used when building a schema from SDL or a parsed SDL document.


Members
NameTypeDescription
assumeValidSDL?booleanSet to true to assume the SDL is valid.
Default: false

Category: Introspection

Functions

buildClientSchema()

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.

Signature:

buildClientSchema(
  introspection: IntrospectionQuery,
  options?: GraphQLSchemaValidationOptions,
): GraphQLSchema;

Arguments
NameTypeDescription
introspectionIntrospectionQueryIntrospection result data to build from.
options?GraphQLSchemaValidationOptionsOptional configuration for this operation.

Returns
TypeDescription
GraphQLSchemaThe client schema represented by the introspection result.

Example
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'

getIntrospectionQuery()

Produce the GraphQL query recommended for a full schema introspection. Accepts optional IntrospectionOptions.

Signature:

getIntrospectionQuery(options?: IntrospectionOptions): string;

Arguments
NameTypeDescription
options?IntrospectionOptionsOptional configuration for this operation.

Returns
TypeDescription
stringThe resolved introspection query.

Example 1
// 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 2
// 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

introspectionFromSchema()

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.

Signature:

introspectionFromSchema(
  schema: GraphQLSchema,
  options?: IntrospectionOptions,
): IntrospectionQuery;

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.
options?IntrospectionOptionsOptional configuration for this operation.

Returns
TypeDescription
IntrospectionQueryIntrospection result data for the schema.

Example 1
// 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 2
// This variant disables optional introspection metadata.
import { buildSchema, introspectionFromSchema } from 'graphql/utilities';
 
const schema = buildSchema(`
  scalar Url @specifiedBy(url: "https://url.spec.whatwg.org/")
 
  type Query {
    homepage: Url
  }
`);
 
const introspection = introspectionFromSchema(schema, {
  descriptions: false,
  specifiedByUrl: false,
  directiveIsRepeatable: false,
  schemaDescription: false,
  inputValueDeprecation: false,
  experimentalDirectiveDeprecation: false,
  oneOf: false,
});
const urlType = introspection.__schema.types.find((type) => type.name === 'Url');
const deprecatedDirective = introspection.__schema.directives.find(
  (directive) => directive.name === 'deprecated',
);
 
urlType.specifiedByURL; // => undefined
urlType.description; // => undefined
introspection.__schema.description; // => undefined
deprecatedDirective.isRepeatable; // => undefined

Types

IntrospectionOptions

Interface. Options controlling which fields are included in the introspection query.


Members
NameTypeDescription
descriptions?booleanWhether to include descriptions in the introspection result.
Default: true
specifiedByUrl?booleanWhether to include specifiedByURL in the introspection result.
Default: false
directiveIsRepeatable?booleanWhether to include isRepeatable flag on directives.
Default: false
schemaDescription?booleanWhether to include description field on schema.
Default: false
inputValueDeprecation?booleanWhether target GraphQL server support deprecation of input values.
Default: false
experimentalDirectiveDeprecation?booleanWhether target GraphQL server supports deprecation of directives.
Default: false
oneOf?booleanWhether target GraphQL server supports @oneOf input objects.
Default: false
typeDepth?numberHow 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

IntrospectionQuery

Interface. The result shape returned by a full introspection query.


Members
NameTypeDescription
__schemaIntrospectionSchemaThe schema.

IntrospectionSchema

Interface. The introspection representation of a GraphQL schema.


Members
NameTypeDescription
description?Maybe<string>Human-readable description for this schema element, if provided.
queryTypeIntrospectionNamedTypeRef<IntrospectionObjectType>The root object type used for query operations.
mutationTypeMaybe<IntrospectionNamedTypeRef<IntrospectionObjectType>>The root object type used for mutation operations, if supported.
subscriptionTypeMaybe<IntrospectionNamedTypeRef<IntrospectionObjectType>>The root object type used for subscription operations, if supported.
typesreadonly IntrospectionType[]Object types that belong to this union type.
directivesreadonly IntrospectionDirective[]Directives available in this schema or applied to this AST node.

IntrospectionType

Type alias. Any introspection representation of a GraphQL type.

type IntrospectionType =
  | IntrospectionScalarType
  | IntrospectionObjectType
  | IntrospectionInterfaceType
  | IntrospectionUnionType
  | IntrospectionEnumType
  | IntrospectionInputObjectType;

IntrospectionOutputType

Type alias. An introspection type that can appear in output position.

type IntrospectionOutputType =
  | IntrospectionScalarType
  | IntrospectionObjectType
  | IntrospectionInterfaceType
  | IntrospectionUnionType
  | IntrospectionEnumType;

IntrospectionInputType

Type alias. An introspection type that can appear in input position.

type IntrospectionInputType =
  | IntrospectionScalarType
  | IntrospectionEnumType
  | IntrospectionInputObjectType;

IntrospectionScalarType

Interface. The introspection representation of a scalar type.


Members
NameTypeDescription
kind'SCALAR'The introspection kind discriminator for this type reference or type.
namestringThe GraphQL name for this schema element.
description?Maybe<string>Human-readable description for this schema element, if provided.
specifiedByURL?Maybe<string>URL identifying the behavior specified for this custom scalar.

IntrospectionObjectType

Interface. The introspection representation of an object type.


Members
NameTypeDescription
kind'OBJECT'The introspection kind discriminator for this type reference or type.
namestringThe GraphQL name for this schema element.
description?Maybe<string>Human-readable description for this schema element, if provided.
fieldsreadonly IntrospectionField[]Fields declared by this object, interface, input object, or literal.
interfacesreadonly IntrospectionNamedTypeRef<IntrospectionInterfaceType>[]Interfaces implemented by this object or interface type.

IntrospectionInterfaceType

Interface. The introspection representation of an interface type.


Members
NameTypeDescription
kind'INTERFACE'The introspection kind discriminator for this type reference or type.
namestringThe GraphQL name for this schema element.
description?Maybe<string>Human-readable description for this schema element, if provided.
fieldsreadonly IntrospectionField[]Fields declared by this object, interface, input object, or literal.
interfacesreadonly IntrospectionNamedTypeRef<IntrospectionInterfaceType>[]Interfaces implemented by this object or interface type.
possibleTypesreadonly IntrospectionNamedTypeRef<IntrospectionObjectType>[]Object types that may be returned for this abstract type.

IntrospectionUnionType

Interface. The introspection representation of a union type.


Members
NameTypeDescription
kind'UNION'The introspection kind discriminator for this type reference or type.
namestringThe GraphQL name for this schema element.
description?Maybe<string>Human-readable description for this schema element, if provided.
possibleTypesreadonly IntrospectionNamedTypeRef<IntrospectionObjectType>[]Object types that may be returned for this abstract type.

IntrospectionEnumType

Interface. The introspection representation of an enum type.


Members
NameTypeDescription
kind'ENUM'The introspection kind discriminator for this type reference or type.
namestringThe GraphQL name for this schema element.
description?Maybe<string>Human-readable description for this schema element, if provided.
enumValuesreadonly IntrospectionEnumValue[]Values declared by this enum type.

IntrospectionInputObjectType

Interface. The introspection representation of an input object type.


Members
NameTypeDescription
kind'INPUT_OBJECT'The introspection kind discriminator for this type reference or type.
namestringThe GraphQL name for this schema element.
description?Maybe<string>Human-readable description for this schema element, if provided.
inputFieldsreadonly IntrospectionInputValue[]Input fields declared by this input object type.
isOneOfbooleanWhether this input object uses the experimental OneOf input object semantics.

IntrospectionListTypeRef

Interface. The introspection representation of a list type reference.


Type Parameters
NameConstraintDefaultDescription
TIntrospectionTypeRefIntrospectionTypeRefThe introspection type reference wrapped by this list type reference.

Members
NameTypeDescription
kind'LIST'The introspection kind discriminator for this type reference or type.
ofTypeTThe type wrapped by this list or non-null type.

IntrospectionNonNullTypeRef

Interface. The introspection representation of a non-null type reference.


Type Parameters
NameConstraintDefaultDescription
TIntrospectionTypeRefIntrospectionTypeRefThe introspection type reference wrapped by this non-null type reference.

Members
NameTypeDescription
kind'NON_NULL'The introspection kind discriminator for this type reference or type.
ofTypeTThe type wrapped by this list or non-null type.

IntrospectionTypeRef

Type alias. Any introspection representation of a type reference.

type IntrospectionTypeRef =
  | IntrospectionNamedTypeRef
  | IntrospectionListTypeRef
  | IntrospectionNonNullTypeRef<IntrospectionNamedTypeRef | IntrospectionListTypeRef>;

IntrospectionOutputTypeRef

Type alias. An introspection type reference that can appear in output position.

type IntrospectionOutputTypeRef =
  | IntrospectionNamedTypeRef<IntrospectionOutputType>
  | IntrospectionListTypeRef<IntrospectionOutputTypeRef>
  | IntrospectionNonNullTypeRef<
      | IntrospectionNamedTypeRef<IntrospectionOutputType>
      | IntrospectionListTypeRef<IntrospectionOutputTypeRef>
    >;

IntrospectionInputTypeRef

Type alias. An introspection type reference that can appear in input position.

type IntrospectionInputTypeRef =
  | IntrospectionNamedTypeRef<IntrospectionInputType>
  | IntrospectionListTypeRef<IntrospectionInputTypeRef>
  | IntrospectionNonNullTypeRef<
      | IntrospectionNamedTypeRef<IntrospectionInputType>
      | IntrospectionListTypeRef<IntrospectionInputTypeRef>
    >;

IntrospectionNamedTypeRef

Interface. The introspection representation of a named type reference.


Type Parameters
NameConstraintDefaultDescription
TIntrospectionTypeIntrospectionTypeThe introspection type represented by this named type reference.

Members
NameTypeDescription
kindT['kind']The introspection kind discriminator for this type reference or type.
namestringThe GraphQL name for this schema element.

IntrospectionField

Interface. The introspection representation of a field.


Members
NameTypeDescription
namestringThe GraphQL name for this schema element.
description?Maybe<string>Human-readable description for this schema element, if provided.
argsreadonly IntrospectionInputValue[]Arguments accepted by this field or directive.
typeIntrospectionOutputTypeRefThe GraphQL type reference or runtime type for this element.
isDeprecatedbooleanWhether this field, argument, enum value, or input value is deprecated.
deprecationReasonMaybe<string>Reason this element is deprecated, if one was provided.

IntrospectionInputValue

Interface. The introspection representation of an argument or input field.


Members
NameTypeDescription
namestringThe GraphQL name for this schema element.
description?Maybe<string>Human-readable description for this schema element, if provided.
typeIntrospectionInputTypeRefThe GraphQL type reference or runtime type for this element.
defaultValueMaybe<string>Default value used when no explicit value is supplied.
isDeprecated?booleanWhether this field, argument, enum value, or input value is deprecated.
deprecationReason?Maybe<string>Reason this element is deprecated, if one was provided.

IntrospectionEnumValue

Interface. The introspection representation of an enum value.


Members
NameTypeDescription
namestringThe GraphQL name for this schema element.
description?Maybe<string>Human-readable description for this schema element, if provided.
isDeprecatedbooleanWhether this field, argument, enum value, or input value is deprecated.
deprecationReasonMaybe<string>Reason this element is deprecated, if one was provided.

IntrospectionDirective

Interface. The introspection representation of a directive.


Members
NameTypeDescription
namestringThe GraphQL name for this schema element.
description?Maybe<string>Human-readable description for this schema element, if provided.
isRepeatable?booleanWhether this directive may appear more than once at the same location.
isDeprecated?booleanWhether this field, argument, enum value, or input value is deprecated.
deprecationReason?Maybe<string>Reason this element is deprecated, if one was provided.
locationsreadonly DirectiveLocation[]Locations where this directive may be applied.
argsreadonly IntrospectionInputValue[]Arguments accepted by this field or directive.

Category: AST Utilities

Functions

concatAST()

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.

Signature:

concatAST(
  documents: readonly DocumentNode[],
): DocumentNode;

Arguments
NameTypeDescription
documentsreadonly DocumentNode[]Document ASTs to concatenate.

Returns
TypeDescription
DocumentNodeA document AST containing all definitions from the provided documents.

Example
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()

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.

Signature:

separateOperations(
  documentAST: DocumentNode,
): ObjMap<DocumentNode>;

Arguments
NameTypeDescription
documentASTDocumentNodeThe parsed GraphQL document AST.

Returns
TypeDescription
ObjMap<DocumentNode>A map of operation names to documents containing each operation and its referenced fragments.

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

stripIgnoredCharacters()

Strips characters that are not significant to the validity or execution of a GraphQL document:

  • UnicodeBOM
  • WhiteSpace
  • LineTerminator
  • Comment
  • Comma
  • BlockString indentation

Note: It is required to have a delimiter character between neighboring non-punctuator tokens and this function always uses single space as delimiter.

It is guaranteed that both input and output documents if parsed would result in the exact same AST except for nodes location.

Warning: It is guaranteed that this function will always produce stable results. However, it’s not guaranteed that it will stay the same between different releases due to bugfixes or changes in the GraphQL specification.

Signature:

stripIgnoredCharacters(
  source: string | Source,
): string;

Arguments
NameTypeDescription
sourcestring | SourceThe GraphQL source text or source object.

Returns
TypeDescription
stringA semantically equivalent GraphQL source string without ignored characters.

Example 1
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 2
"""
Type description
"""
type Foo {
  """
  Field description
  """
  bar: String
}

Becomes:

"""Type description""" type Foo{"""Field description""" bar:String}

Example 3
import { stripIgnoredCharacters } from 'graphql/utilities';
 
const source = stripIgnoredCharacters('query Example { name }');
 
source; // => 'query Example{name}'

Category: Schema Changes

Functions

findBreakingChanges() Deprecated

Given two schemas, returns an Array containing descriptions of all the types of breaking changes covered by the other functions down below. This deprecated wrapper will be removed in v18; use findSchemaChanges() instead and filter for breaking changes.

Signature:

findBreakingChanges(
  oldSchema: GraphQLSchema,
  newSchema: GraphQLSchema,
): BreakingChange[];

Arguments
NameTypeDescription
oldSchemaGraphQLSchemaSchema before the change.
newSchemaGraphQLSchemaSchema after the change.

Returns
TypeDescription
BreakingChange[]Breaking changes between the two schemas.

Example
import { buildSchema, findBreakingChanges } from 'graphql/utilities';
 
const oldSchema = buildSchema(`
  type Query {
    greeting: String
  }
`);
const newSchema = buildSchema(`
  type Query {
    hello: String
  }
`);
 
const changes = findBreakingChanges(oldSchema, newSchema);
 
changes.map((change) => change.type); // => ['FIELD_REMOVED']

findDangerousChanges() Deprecated

Given two schemas, returns an Array containing descriptions of all the types of potentially dangerous changes covered by the other functions down below. This deprecated wrapper will be removed in v18; use findSchemaChanges() instead and filter for dangerous changes.

Signature:

findDangerousChanges(
  oldSchema: GraphQLSchema,
  newSchema: GraphQLSchema,
): DangerousChange[];

Arguments
NameTypeDescription
oldSchemaGraphQLSchemaSchema before the change.
newSchemaGraphQLSchemaSchema after the change.

Returns
TypeDescription
DangerousChange[]Dangerous changes between the two schemas.

Example
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.map((change) => change.type); // => ['VALUE_ADDED_TO_ENUM']

findSchemaChanges()

Finds all schema changes between two schemas.

Signature:

findSchemaChanges(
  oldSchema: GraphQLSchema,
  newSchema: GraphQLSchema,
): SchemaChange[];

Arguments
NameTypeDescription
oldSchemaGraphQLSchemaSchema before the change.
newSchemaGraphQLSchemaSchema after the change.

Returns
TypeDescription
SchemaChange[]Safe, dangerous, and breaking changes between the two schemas.

Example
import { buildSchema, findSchemaChanges } from 'graphql/utilities';
 
const oldSchema = buildSchema(`
  type Query {
    greeting: String
  }
`);
const newSchema = buildSchema(`
  type Query {
    greeting(name: String): String
    farewell: String
  }
`);
 
const changes = findSchemaChanges(oldSchema, newSchema);
 
changes.map((change) => change.type); // => ['OPTIONAL_ARG_ADDED', 'FIELD_ADDED']

Enumerations

BreakingChangeType

Enumeration. Categories of schema changes that may break existing operations.

This is not a TypeScript enum. GraphQL.js exports BreakingChangeType as both a runtime const object of literal values and a TypeScript type alias for those values.


Members
NameValue
TYPE_REMOVED"TYPE_REMOVED"
TYPE_CHANGED_KIND"TYPE_CHANGED_KIND"
TYPE_REMOVED_FROM_UNION"TYPE_REMOVED_FROM_UNION"
VALUE_REMOVED_FROM_ENUM"VALUE_REMOVED_FROM_ENUM"
REQUIRED_INPUT_FIELD_ADDED"REQUIRED_INPUT_FIELD_ADDED"
IMPLEMENTED_INTERFACE_REMOVED"IMPLEMENTED_INTERFACE_REMOVED"
FIELD_REMOVED"FIELD_REMOVED"
FIELD_CHANGED_KIND"FIELD_CHANGED_KIND"
REQUIRED_ARG_ADDED"REQUIRED_ARG_ADDED"
ARG_REMOVED"ARG_REMOVED"
ARG_CHANGED_KIND"ARG_CHANGED_KIND"
DIRECTIVE_REMOVED"DIRECTIVE_REMOVED"
DIRECTIVE_ARG_REMOVED"DIRECTIVE_ARG_REMOVED"
REQUIRED_DIRECTIVE_ARG_ADDED"REQUIRED_DIRECTIVE_ARG_ADDED"
DIRECTIVE_REPEATABLE_REMOVED"DIRECTIVE_REPEATABLE_REMOVED"
DIRECTIVE_LOCATION_REMOVED"DIRECTIVE_LOCATION_REMOVED"

DangerousChangeType

Enumeration. Categories of schema changes that may be dangerous for existing operations.

This is not a TypeScript enum. GraphQL.js exports DangerousChangeType as both a runtime const object of literal values and a TypeScript type alias for those values.


Members
NameValue
VALUE_ADDED_TO_ENUM"VALUE_ADDED_TO_ENUM"
TYPE_ADDED_TO_UNION"TYPE_ADDED_TO_UNION"
OPTIONAL_INPUT_FIELD_ADDED"OPTIONAL_INPUT_FIELD_ADDED"
OPTIONAL_ARG_ADDED"OPTIONAL_ARG_ADDED"
IMPLEMENTED_INTERFACE_ADDED"IMPLEMENTED_INTERFACE_ADDED"
ARG_DEFAULT_VALUE_CHANGE"ARG_DEFAULT_VALUE_CHANGE"

SafeChangeType

Enumeration. Categories of schema changes that are considered safe for existing operations.

This is not a TypeScript enum. GraphQL.js exports SafeChangeType as both a runtime const object of literal values and a TypeScript type alias for those values.


Members
NameValue
DESCRIPTION_CHANGED"DESCRIPTION_CHANGED"
TYPE_ADDED"TYPE_ADDED"
OPTIONAL_INPUT_FIELD_ADDED"OPTIONAL_INPUT_FIELD_ADDED"
OPTIONAL_ARG_ADDED"OPTIONAL_ARG_ADDED"
DIRECTIVE_ADDED"DIRECTIVE_ADDED"
FIELD_ADDED"FIELD_ADDED"
DIRECTIVE_REPEATABLE_ADDED"DIRECTIVE_REPEATABLE_ADDED"
DIRECTIVE_LOCATION_ADDED"DIRECTIVE_LOCATION_ADDED"
OPTIONAL_DIRECTIVE_ARG_ADDED"OPTIONAL_DIRECTIVE_ARG_ADDED"
FIELD_CHANGED_KIND_SAFE"FIELD_CHANGED_KIND_SAFE"
ARG_CHANGED_KIND_SAFE"ARG_CHANGED_KIND_SAFE"
ARG_DEFAULT_VALUE_ADDED"ARG_DEFAULT_VALUE_ADDED"

Types

BreakingChange

Interface. Description of a schema change that may break existing operations.


Members
NameTypeDescription
typeBreakingChangeTypeSpecific kind of breaking schema change.
descriptionstringHuman-readable description of the breaking schema change.

DangerousChange

Interface. Description of a schema change that may be dangerous for existing operations.


Members
NameTypeDescription
typeDangerousChangeTypeSpecific kind of dangerous schema change.
descriptionstringHuman-readable description of the dangerous schema change.

SafeChange

Interface. Description of a schema change that is considered safe for existing operations.


Members
NameTypeDescription
typeSafeChangeTypeSpecific kind of safe schema change.
descriptionstringHuman-readable description of the safe schema change.

SchemaChange

Type alias. Any schema change detected between two schemas.

type SchemaChange =
  | SafeChange
  | DangerousChange
  | BreakingChange;

Category: Operations

Functions

getOperationAST()

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.

Signature:

getOperationAST(
  documentAST: DocumentNode,
  operationName?: Maybe<string>,
): Maybe<OperationDefinitionNode>;

Arguments
NameTypeDescription
documentASTDocumentNodeThe parsed GraphQL document AST.
operationName?Maybe<string>The optional operation name to select.

Returns
TypeDescription
Maybe<OperationDefinitionNode>The resolved operation ast.

Example
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

Category: Schema Printing

Functions

printSchema()

Prints the schema.

Signature:

printSchema(schema: GraphQLSchema): string;

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.

Returns
TypeDescription
stringThe printed string representation.

Example
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')

printIntrospectionSchema()

Prints the introspection schema.

Signature:

printIntrospectionSchema(schema: GraphQLSchema): string;

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.

Returns
TypeDescription
stringThe printed string representation.

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

printType()

Prints the type.

Signature:

printType(type: GraphQLNamedType): string;

Arguments
NameTypeDescription
typeGraphQLNamedTypeThe GraphQL type to inspect.

Returns
TypeDescription
stringThe printed string representation.

Example
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')

printDirective()

Prints a directive definition in GraphQL SDL.

Signature:

printDirective(directive: GraphQLDirective): string;

Arguments
NameTypeDescription
directiveGraphQLDirectiveDirective to print.

Returns
TypeDescription
stringSDL string for the directive definition.

Example
import { DirectiveLocation, GraphQLDirective, GraphQLString } from 'graphql/type';
import { printDirective } from 'graphql/utilities';
 
const authDirective = new GraphQLDirective({
  name: 'auth',
  description: 'Requires authorization.',
  locations: [DirectiveLocation.FIELD_DEFINITION],
  args: {
    scope: { type: GraphQLString },
  },
});
 
printDirective(authDirective); // => '"""Requires authorization."""\ndirective @auth(scope: String) on FIELD_DEFINITION'

Category: Schema Coordinates

Functions

resolveSchemaCoordinate()

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

Signature:

resolveSchemaCoordinate(
  schema: GraphQLSchema,
  schemaCoordinate: string | Source,
): ResolvedSchemaElement | undefined;

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.
schemaCoordinatestring | SourceThe schema coordinate to resolve.

Returns
TypeDescription
ResolvedSchemaElement | undefinedThe schema element identified by the coordinate, or undefined if none exists.

Example
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

resolveASTSchemaCoordinate()

Resolves schema coordinate from a parsed SchemaCoordinate node.

Signature:

resolveASTSchemaCoordinate(
  schema: GraphQLSchema,
  schemaCoordinate: SchemaCoordinateNode,
): ResolvedSchemaElement | undefined;

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.
schemaCoordinateSchemaCoordinateNodeThe schema coordinate to resolve.

Returns
TypeDescription
ResolvedSchemaElement | undefinedThe schema element identified by the parsed coordinate, or undefined if none exists.

Example
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'

Types

ResolvedSchemaElement

Type alias. A schema element resolved from a schema coordinate.

type ResolvedSchemaElement =
  | ResolvedNamedType
  | ResolvedField
  | ResolvedInputField
  | ResolvedEnumValue
  | ResolvedFieldArgument
  | ResolvedDirective
  | ResolvedDirectiveArgument;

Category: Type Comparisons

Functions

isEqualType()

Provided two types, return true if the types are equal (invariant).

Signature:

isEqualType(
  typeA: GraphQLType,
  typeB: GraphQLType,
): boolean;

Arguments
NameTypeDescription
typeAGraphQLTypeThe first GraphQL type to compare.
typeBGraphQLTypeThe second GraphQL type to compare.

Returns
TypeDescription
booleanTrue when both types are equal.

Example
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

isTypeSubTypeOf()

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).

Signature:

isTypeSubTypeOf(
  schema: GraphQLSchema,
  maybeSubType: GraphQLType,
  superType: GraphQLType,
): boolean;

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.
maybeSubTypeGraphQLTypeThe possible subtype to compare.
superTypeGraphQLTypeThe possible supertype to compare.

Returns
TypeDescription
booleanTrue when maybeSubType is equal to or a subtype of superType.

Example
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

doTypesOverlap()

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.

Signature:

doTypesOverlap(
  schema: GraphQLSchema,
  typeA: GraphQLCompositeType,
  typeB: GraphQLCompositeType,
): boolean;

Arguments
NameTypeDescription
schemaGraphQLSchemaGraphQL schema to use.
typeAGraphQLCompositeTypeThe first GraphQL type to compare.
typeBGraphQLCompositeTypeThe second GraphQL type to compare.

Returns
TypeDescription
booleanTrue when the two composite types can apply to at least one common object type.

Example
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

Category: Typed Documents

Types

TypedQueryDocumentNode

Interface. Wrapper type that contains DocumentNode and types that can be deduced from it.


Type Parameters
NameConstraintDefaultDescription
TResponseData{ [key: string]: any }Typed GraphQL response data shape.
TRequestVariables{ [key: string]: any }Typed GraphQL request variables shape.
interface TypedQueryDocumentNode<
  TResponseData = { [key: string]: any },
  TRequestVariables = { [key: string]: any },
> extends DocumentNode

Members
NameTypeDescription
definitionsreadonly ExecutableDefinitionNode[]Top-level executable and type-system definitions in this document.
__ensureTypesOfVariablesAndResultMatching?(variables: TRequestVariables) => TResponseDataThis 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