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:
- Type Info
- Values
- Schema Construction
- Introspection
- AST Utilities
- Schema Changes
- Operations
- Schema Printing
- Schema Coordinates
- Type Comparisons
- Typed Documents
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>
>,
);
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | Schema 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>;
| Type | Description |
|---|---|
Maybe<GraphQLOutputType> | The current output type, if known. |
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>;
| Type | Description |
|---|---|
Maybe<GraphQLCompositeType> | The current parent composite type, if known. |
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>;
| Type | Description |
|---|---|
Maybe<GraphQLInputType> | The current input type, if known. |
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>;
| Type | Description |
|---|---|
Maybe<GraphQLInputType> | The parent input type, if known. |
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>
>;
| Type | Description |
|---|---|
Maybe<GraphQLField<unknown, unknown>> | The current field definition, if known. |
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;
| Type | Description |
|---|---|
unknown | The current default input, if one is available. |
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>;
| Type | Description |
|---|---|
Maybe<GraphQLDirective> | The current directive definition, if known. |
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>;
| Type | Description |
|---|---|
Maybe<GraphQLArgument> | The current argument definition, if known. |
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>;
| Type | Description |
|---|---|
Maybe<FragmentSignature> | The fragment signature for the current fragment definition. |
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>;
| Type | Description |
|---|---|
(
fragmentName: string,
) => Maybe<FragmentSignature> | A function that maps fragment names to fragment signatures. |
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>;
| Type | Description |
|---|---|
Maybe<VariableDefinitionNode> | The variable definition for the current fragment argument. |
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>;
| Type | Description |
|---|---|
Maybe<GraphQLEnumValue> | The current enum value definition, if known. |
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;
| Name | Type | Description |
|---|---|---|
| node | ASTNode | AST node being entered. |
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;
| Name | Type | Description |
|---|---|---|
| node | ASTNode | AST node being entered. |
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(); // => undefinedFunctions
visitWithTypeInfo()
Creates a new visitor instance which maintains a provided TypeInfo instance along with visiting visitor.
Signature:
visitWithTypeInfo(
typeInfo: TypeInfo,
visitor: ASTVisitor,
): ASTVisitor;
| Name | Type | Description |
|---|---|---|
| typeInfo | TypeInfo | TypeInfo instance to update during traversal. |
| visitor | ASTVisitor | Visitor callbacks to wrap with TypeInfo updates. |
| Type | Description |
|---|---|
ASTVisitor | A visitor that keeps TypeInfo in sync while delegating callbacks. |
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()coerceInputValue()coerceInputLiteral()replaceVariables()validateInputValue()validateInputLiteral()valueFromAST()valueFromASTUntyped()valueToLiteral()
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 Value | GraphQL Value |
|---|---|
| Object | Input Object |
| Array | List |
| Boolean | Boolean |
| String | String / Enum Value |
| Number | Int / Float |
| BigInt | Int |
| Unknown | Enum Value |
| null | NullValue |
Signature:
astFromValue(
value: unknown,
type: GraphQLInputType,
): Maybe<ConstValueNode>;
| Name | Type | Description |
|---|---|---|
| value | unknown | Runtime value to convert. |
| type | GraphQLInputType | The GraphQL type to inspect. |
| Type | Description |
|---|---|
Maybe<ConstValueNode> | A GraphQL value AST for the provided JavaScript value, or null when no literal can represent it. |
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)); // => nullcoerceInputValue()
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;
| Name | Type | Description |
|---|---|---|
| inputValue | unknown | JavaScript value to coerce. |
| type | GraphQLInputType | GraphQL input type to coerce the value against. |
| Type | Description |
|---|---|
unknown | Coerced value, or undefined if coercion fails. |
// 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); // => undefinedcoerceInputLiteral()
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;
| Name | Type | Description |
|---|---|---|
| valueNode | ValueNode | GraphQL value AST node to coerce. |
| type | GraphQLInputType | GraphQL 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. |
| Type | Description |
|---|---|
unknown | Coerced value, or undefined if coercion fails. |
// 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// 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); // => 4replaceVariables()
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;
| Name | Type | Description |
|---|---|---|
| valueNode | ValueNode | Value 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. |
| Type | Description |
|---|---|
ConstValueNode | A constant value AST with variables replaced. |
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;
| Name | Type | Description |
|---|---|---|
| inputValue | unknown | JavaScript value to validate. |
| type | GraphQLInputType | GraphQL input type to validate the value against. |
| onError | (
error: GraphQLError,
path: readonly (string | number)[],
) => void | Callback invoked for each validation error and path. |
| hideSuggestions? | Maybe<boolean> | Whether suggestion text should be omitted from errors. |
// 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'] } ]// 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;
| Name | Type | Description |
|---|---|---|
| valueNode | ValueNode | GraphQL value AST node to validate. |
| type | GraphQLInputType | GraphQL input type to validate the literal against. |
| onError | (
error: GraphQLError,
path: readonly (string | number)[],
) => void | Callback 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. |
// 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'] } ]// 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 Value | JSON Value |
|---|---|
| Input Object | Object |
| List | Array |
| Boolean | Boolean |
| String | String |
| Int / Float | Number |
| Enum Value | Unknown |
| NullValue | null |
Signature:
valueFromAST(
valueNode: Maybe<ValueNode>,
type: GraphQLInputType,
variables?: Maybe<ObjMap<unknown>>,
): unknown;
| Name | Type | Description |
|---|---|---|
| valueNode | Maybe<ValueNode> | GraphQL value AST node to convert. |
| type | GraphQLInputType | The GraphQL type to inspect. |
| variables? | Maybe<ObjMap<unknown>> | Optional runtime variable values keyed by variable name. |
| Type | Description |
|---|---|
unknown | The coerced JavaScript value, or undefined if the AST value cannot be coerced to the type. |
// 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// 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, {}); // => undefinedvalueFromASTUntyped()
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 |
Signature:
valueFromASTUntyped(
valueNode: ValueNode,
variables?: Maybe<ObjMap<unknown>>,
): unknown;
| Name | Type | Description |
|---|---|---|
| valueNode | ValueNode | GraphQL value AST node to convert. |
| variables? | Maybe<ObjMap<unknown>> | Optional runtime variable values keyed by variable name. |
| Type | Description |
|---|---|
unknown | JavaScript value represented by the GraphQL value AST. |
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;
| Name | Type | Description |
|---|---|---|
| value | unknown | JavaScript value to convert. |
| type | GraphQLInputType | GraphQL input type to convert the value against. |
| Type | Description |
|---|---|
ConstValueNode | undefined | A GraphQL value AST, or undefined if the value is invalid. |
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); // => undefinedCategory: Schema Construction
Functions:
buildASTSchema()buildSchema()extendSchema()lexicographicSortSchema()
Types:
BuildSchemaOptions
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;
| Name | Type | Description |
|---|---|---|
| documentAST | DocumentNode | The parsed GraphQL document AST. |
| options? | BuildSchemaOptions | Optional configuration for this operation. |
| Type | Description |
|---|---|
GraphQLSchema | The schema built from the provided SDL document. |
// 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'// 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 throwbuildSchema()
Builds a GraphQLSchema directly from a schema definition language source.
Signature:
buildSchema(
source: string | Source,
options?: BuildSchemaOptions & ParseOptions,
): GraphQLSchema;
| Name | Type | Description |
|---|---|---|
| source | string | Source | The GraphQL source text or source object. |
| options? | BuildSchemaOptions & ParseOptions | Optional configuration for this operation. |
| Type | Description |
|---|---|
GraphQLSchema | The schema built from the provided SDL document. |
// 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'// 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; // => undefinedextendSchema()
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;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| documentAST | DocumentNode | The parsed GraphQL document AST. |
| options? | { assumeValidSDL?: boolean | undefined } | Optional configuration for this operation. |
| Type | Description |
|---|---|
GraphQLSchema | A new schema with the extensions and definitions applied. |
// 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']// 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 throwlexicographicSortSchema()
Sort GraphQLSchema.
This function returns a sorted copy of the given GraphQLSchema.
Signature:
lexicographicSortSchema(
schema: GraphQLSchema,
): GraphQLSchema;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| Type | Description |
|---|---|
GraphQLSchema | A copy of the schema with types, fields, arguments, and values sorted lexicographically. |
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.
| Name | Type | Description |
|---|---|---|
| assumeValidSDL? | boolean | Set to true to assume the SDL is valid. Default: false |
Category: Introspection
Functions:
buildClientSchema()getIntrospectionQuery()introspectionFromSchema()
Types:
IntrospectionOptionsIntrospectionQueryIntrospectionSchemaIntrospectionTypeIntrospectionOutputTypeIntrospectionInputTypeIntrospectionScalarTypeIntrospectionObjectTypeIntrospectionInterfaceTypeIntrospectionUnionTypeIntrospectionEnumTypeIntrospectionInputObjectTypeIntrospectionListTypeRefIntrospectionNonNullTypeRefIntrospectionTypeRefIntrospectionOutputTypeRefIntrospectionInputTypeRefIntrospectionNamedTypeRefIntrospectionFieldIntrospectionInputValueIntrospectionEnumValueIntrospectionDirective
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;
| Name | Type | Description |
|---|---|---|
| introspection | IntrospectionQuery | Introspection result data to build from. |
| options? | GraphQLSchemaValidationOptions | Optional configuration for this operation. |
| Type | Description |
|---|---|
GraphQLSchema | The client schema represented by the introspection result. |
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;
| Name | Type | Description |
|---|---|---|
| options? | IntrospectionOptions | Optional configuration for this operation. |
| Type | Description |
|---|---|
string | The resolved introspection query. |
// Generate the default introspection query.
import { getIntrospectionQuery } from 'graphql/utilities';
const query = getIntrospectionQuery();
query; // matches /__schema/
query; // matches /description/
query; // does not match /specifiedByURL/// 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; // => trueintrospectionFromSchema()
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;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| options? | IntrospectionOptions | Optional configuration for this operation. |
| Type | Description |
|---|---|
IntrospectionQuery | Introspection result data for the schema. |
// 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/'// 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; // => undefinedTypes
IntrospectionOptions
Interface. Options controlling which fields are included in the introspection query.
| Name | Type | Description |
|---|---|---|
| descriptions? | boolean | Whether to include descriptions in the introspection result. Default: true |
| specifiedByUrl? | boolean | Whether to include specifiedByURL in the introspection result.Default: false |
| directiveIsRepeatable? | boolean | Whether to include isRepeatable flag on directives.Default: false |
| schemaDescription? | boolean | Whether to include description field on schema.Default: false |
| inputValueDeprecation? | boolean | Whether target GraphQL server support deprecation of input values. Default: false |
| experimentalDirectiveDeprecation? | boolean | Whether target GraphQL server supports deprecation of directives. Default: false |
| oneOf? | boolean | Whether target GraphQL server supports @oneOf input objects.Default: false |
| typeDepth? | number | 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 |
IntrospectionQuery
Interface. The result shape returned by a full introspection query.
| Name | Type | Description |
|---|---|---|
| __schema | IntrospectionSchema | The schema. |
IntrospectionSchema
Interface. The introspection representation of a GraphQL schema.
| Name | Type | Description |
|---|---|---|
| description? | Maybe<string> | Human-readable description for this schema element, if provided. |
| queryType | IntrospectionNamedTypeRef<IntrospectionObjectType> | The root object type used for query operations. |
| mutationType | Maybe<IntrospectionNamedTypeRef<IntrospectionObjectType>> | The root object type used for mutation operations, if supported. |
| subscriptionType | Maybe<IntrospectionNamedTypeRef<IntrospectionObjectType>> | The root object type used for subscription operations, if supported. |
| types | readonly IntrospectionType[] | Object types that belong to this union type. |
| directives | readonly 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.
| Name | Type | Description |
|---|---|---|
| kind | 'SCALAR' | The introspection kind discriminator for this type reference or type. |
| name | string | The 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.
| Name | Type | Description |
|---|---|---|
| kind | 'OBJECT' | The introspection kind discriminator for this type reference or type. |
| name | string | The GraphQL name for this schema element. |
| description? | Maybe<string> | Human-readable description for this schema element, if provided. |
| fields | readonly IntrospectionField[] | Fields declared by this object, interface, input object, or literal. |
| interfaces | readonly IntrospectionNamedTypeRef<IntrospectionInterfaceType>[] | Interfaces implemented by this object or interface type. |
IntrospectionInterfaceType
Interface. The introspection representation of an interface type.
| Name | Type | Description |
|---|---|---|
| kind | 'INTERFACE' | The introspection kind discriminator for this type reference or type. |
| name | string | The GraphQL name for this schema element. |
| description? | Maybe<string> | Human-readable description for this schema element, if provided. |
| fields | readonly IntrospectionField[] | Fields declared by this object, interface, input object, or literal. |
| interfaces | readonly IntrospectionNamedTypeRef<IntrospectionInterfaceType>[] | Interfaces implemented by this object or interface type. |
| possibleTypes | readonly IntrospectionNamedTypeRef<IntrospectionObjectType>[] | Object types that may be returned for this abstract type. |
IntrospectionUnionType
Interface. The introspection representation of a union type.
| Name | Type | Description |
|---|---|---|
| kind | 'UNION' | The introspection kind discriminator for this type reference or type. |
| name | string | The GraphQL name for this schema element. |
| description? | Maybe<string> | Human-readable description for this schema element, if provided. |
| possibleTypes | readonly IntrospectionNamedTypeRef<IntrospectionObjectType>[] | Object types that may be returned for this abstract type. |
IntrospectionEnumType
Interface. The introspection representation of an enum type.
| Name | Type | Description |
|---|---|---|
| kind | 'ENUM' | The introspection kind discriminator for this type reference or type. |
| name | string | The GraphQL name for this schema element. |
| description? | Maybe<string> | Human-readable description for this schema element, if provided. |
| enumValues | readonly IntrospectionEnumValue[] | Values declared by this enum type. |
IntrospectionInputObjectType
Interface. The introspection representation of an input object type.
| Name | Type | Description |
|---|---|---|
| kind | 'INPUT_OBJECT' | The introspection kind discriminator for this type reference or type. |
| name | string | The GraphQL name for this schema element. |
| description? | Maybe<string> | Human-readable description for this schema element, if provided. |
| inputFields | readonly IntrospectionInputValue[] | Input fields declared by this input object type. |
| isOneOf | boolean | Whether this input object uses the experimental OneOf input object semantics. |
IntrospectionListTypeRef
Interface. The introspection representation of a list type reference.
| Name | Constraint | Default | Description |
|---|---|---|---|
| T | IntrospectionTypeRef | IntrospectionTypeRef | The introspection type reference wrapped by this list type reference. |
| Name | Type | Description |
|---|---|---|
| kind | 'LIST' | The introspection kind discriminator for this type reference or type. |
| ofType | T | The type wrapped by this list or non-null type. |
IntrospectionNonNullTypeRef
Interface. The introspection representation of a non-null type reference.
| Name | Constraint | Default | Description |
|---|---|---|---|
| T | IntrospectionTypeRef | IntrospectionTypeRef | The introspection type reference wrapped by this non-null type reference. |
| Name | Type | Description |
|---|---|---|
| kind | 'NON_NULL' | The introspection kind discriminator for this type reference or type. |
| ofType | T | The 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.
| Name | Constraint | Default | Description |
|---|---|---|---|
| T | IntrospectionType | IntrospectionType | The introspection type represented by this named type reference. |
| Name | Type | Description |
|---|---|---|
| kind | T['kind'] | The introspection kind discriminator for this type reference or type. |
| name | string | The GraphQL name for this schema element. |
IntrospectionField
Interface. The introspection representation of a field.
| Name | Type | Description |
|---|---|---|
| name | string | The GraphQL name for this schema element. |
| description? | Maybe<string> | Human-readable description for this schema element, if provided. |
| args | readonly IntrospectionInputValue[] | Arguments accepted by this field or directive. |
| type | IntrospectionOutputTypeRef | The GraphQL type reference or runtime type for this element. |
| isDeprecated | boolean | Whether this field, argument, enum value, or input value is deprecated. |
| deprecationReason | Maybe<string> | Reason this element is deprecated, if one was provided. |
IntrospectionInputValue
Interface. The introspection representation of an argument or input field.
| Name | Type | Description |
|---|---|---|
| name | string | The GraphQL name for this schema element. |
| description? | Maybe<string> | Human-readable description for this schema element, if provided. |
| type | IntrospectionInputTypeRef | The GraphQL type reference or runtime type for this element. |
| defaultValue | Maybe<string> | Default value used when no explicit value is supplied. |
| isDeprecated? | boolean | Whether 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.
| Name | Type | Description |
|---|---|---|
| name | string | The GraphQL name for this schema element. |
| description? | Maybe<string> | Human-readable description for this schema element, if provided. |
| isDeprecated | boolean | Whether this field, argument, enum value, or input value is deprecated. |
| deprecationReason | Maybe<string> | Reason this element is deprecated, if one was provided. |
IntrospectionDirective
Interface. The introspection representation of a directive.
| Name | Type | Description |
|---|---|---|
| name | string | The GraphQL name for this schema element. |
| description? | Maybe<string> | Human-readable description for this schema element, if provided. |
| isRepeatable? | boolean | Whether this directive may appear more than once at the same location. |
| isDeprecated? | boolean | Whether this field, argument, enum value, or input value is deprecated. |
| deprecationReason? | Maybe<string> | Reason this element is deprecated, if one was provided. |
| locations | readonly DirectiveLocation[] | Locations where this directive may be applied. |
| args | readonly 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;
| Name | Type | Description |
|---|---|---|
| documents | readonly DocumentNode[] | Document ASTs to concatenate. |
| Type | Description |
|---|---|
DocumentNode | A document AST containing all definitions from the provided documents. |
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; // => 2separateOperations()
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>;
| Name | Type | Description |
|---|---|---|
| documentAST | DocumentNode | The parsed GraphQL document AST. |
| Type | Description |
|---|---|
ObjMap<DocumentNode> | A map of operation names to documents containing each operation and its referenced fragments. |
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;
| Name | Type | Description |
|---|---|---|
| source | string | Source | The GraphQL source text or source object. |
| Type | Description |
|---|---|
string | A semantically equivalent GraphQL source string without ignored characters. |
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}}}"""
Type description
"""
type Foo {
"""
Field description
"""
bar: String
}Becomes:
"""Type description""" type Foo{"""Field description""" bar:String}import { stripIgnoredCharacters } from 'graphql/utilities';
const source = stripIgnoredCharacters('query Example { name }');
source; // => 'query Example{name}'Category: Schema Changes
Functions:
findBreakingChanges()findDangerousChanges()findSchemaChanges()
Enumerations:
BreakingChangeTypeDangerousChangeTypeSafeChangeType
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[];
| Name | Type | Description |
|---|---|---|
| oldSchema | GraphQLSchema | Schema before the change. |
| newSchema | GraphQLSchema | Schema after the change. |
| Type | Description |
|---|---|
BreakingChange[] | Breaking changes between the two schemas. |
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[];
| Name | Type | Description |
|---|---|---|
| oldSchema | GraphQLSchema | Schema before the change. |
| newSchema | GraphQLSchema | Schema after the change. |
| Type | Description |
|---|---|
DangerousChange[] | Dangerous changes between the two schemas. |
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[];
| Name | Type | Description |
|---|---|---|
| oldSchema | GraphQLSchema | Schema before the change. |
| newSchema | GraphQLSchema | Schema after the change. |
| Type | Description |
|---|---|
SchemaChange[] | Safe, dangerous, and breaking changes between the two schemas. |
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 exportsBreakingChangeTypeas both a runtime const object of literal values and a TypeScript type alias for those values.
| Name | Value |
|---|---|
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 exportsDangerousChangeTypeas both a runtime const object of literal values and a TypeScript type alias for those values.
| Name | Value |
|---|---|
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 exportsSafeChangeTypeas both a runtime const object of literal values and a TypeScript type alias for those values.
| Name | Value |
|---|---|
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.
| Name | Type | Description |
|---|---|---|
| type | BreakingChangeType | Specific kind of breaking schema change. |
| description | string | Human-readable description of the breaking schema change. |
DangerousChange
Interface. Description of a schema change that may be dangerous for existing operations.
| Name | Type | Description |
|---|---|---|
| type | DangerousChangeType | Specific kind of dangerous schema change. |
| description | string | Human-readable description of the dangerous schema change. |
SafeChange
Interface. Description of a schema change that is considered safe for existing operations.
| Name | Type | Description |
|---|---|---|
| type | SafeChangeType | Specific kind of safe schema change. |
| description | string | Human-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()
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>;
| Name | Type | Description |
|---|---|---|
| documentAST | DocumentNode | The parsed GraphQL document AST. |
| operationName? | Maybe<string> | The optional operation name to select. |
| Type | Description |
|---|---|
Maybe<OperationDefinitionNode> | The resolved operation ast. |
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'); // => undefinedCategory: Schema Printing
Functions
printSchema()
Prints the schema.
Signature:
printSchema(schema: GraphQLSchema): string;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| Type | Description |
|---|---|
string | The printed string representation. |
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;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| Type | Description |
|---|---|
string | The printed string representation. |
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;
| Name | Type | Description |
|---|---|---|
| type | GraphQLNamedType | The GraphQL type to inspect. |
| Type | Description |
|---|---|
string | The printed string representation. |
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;
| Name | Type | Description |
|---|---|---|
| directive | GraphQLDirective | Directive to print. |
| Type | Description |
|---|---|
string | SDL string for the directive definition. |
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;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| schemaCoordinate | string | Source | The schema coordinate to resolve. |
| Type | Description |
|---|---|
ResolvedSchemaElement | undefined | The schema element identified by the coordinate, or undefined if none exists. |
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'); // => undefinedresolveASTSchemaCoordinate()
Resolves schema coordinate from a parsed SchemaCoordinate node.
Signature:
resolveASTSchemaCoordinate(
schema: GraphQLSchema,
schemaCoordinate: SchemaCoordinateNode,
): ResolvedSchemaElement | undefined;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| schemaCoordinate | SchemaCoordinateNode | The schema coordinate to resolve. |
| Type | Description |
|---|---|
ResolvedSchemaElement | undefined | The schema element identified by the parsed coordinate, or undefined if none exists. |
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;
| Name | Type | Description |
|---|---|---|
| typeA | GraphQLType | The first GraphQL type to compare. |
| typeB | GraphQLType | The second GraphQL type to compare. |
| Type | Description |
|---|---|
boolean | True when both types are equal. |
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); // => falseisTypeSubTypeOf()
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;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| maybeSubType | GraphQLType | The possible subtype to compare. |
| superType | GraphQLType | The possible supertype to compare. |
| Type | Description |
|---|---|
boolean | True when maybeSubType is equal to or a subtype of superType. |
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); // => falsedoTypesOverlap()
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;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| typeA | GraphQLCompositeType | The first GraphQL type to compare. |
| typeB | GraphQLCompositeType | The second GraphQL type to compare. |
| Type | Description |
|---|---|
boolean | True when the two composite types can apply to at least one common object type. |
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); // => falseCategory: Typed Documents
Types:
TypedQueryDocumentNode
Types
TypedQueryDocumentNode
Interface. Wrapper type that contains DocumentNode and types that can be deduced from it.
| Name | Constraint | Default | Description |
|---|---|---|---|
| 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
| Name | Type | Description |
|---|---|---|
| definitions | readonly ExecutableDefinitionNode[] | Top-level executable and type-system definitions in this document. |
| __ensureTypesOfVariablesAndResultMatching? | (variables: TRequestVariables) => TResponseData | 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 |