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
- Validation
- 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>,
getFieldDefFn?: (
schema: GraphQLSchema,
parentType: GraphQLType,
fieldNode: FieldNode,
) => Maybe<GraphQLField<unknown, unknown>>,
);
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | Schema used for type lookups. |
| initialType? | Maybe<GraphQLType> | Optional type to use at the start of traversal. |
| getFieldDefFn? | (
schema: GraphQLSchema,
parentType: GraphQLType,
fieldNode: FieldNode,
) => Maybe<GraphQLField<unknown, unknown>> | Optional field definition lookup override. |
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 value for the current input position.
Signature:
getDefaultValue(): unknown;
| Type | Description |
|---|---|
unknown | The current default value, 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; // => 10getDirective()
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'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: Validation
Functions:
assertValidName()isValidNameError()
Functions
assertValidName()
Upholds the spec rules about naming. This deprecated helper is retained for
backwards compatibility; call assertName instead because assertValidName
will be removed in v17.
Signature:
assertValidName(name: string): string;
| Name | Type | Description |
|---|---|---|
| name | string | The GraphQL name to validate. |
| Type | Description |
|---|---|
string | The validated GraphQL name. |
import { assertValidName } from 'graphql/utilities';
assertValidName('User'); // => 'User'
assertValidName('__typename'); // throws an errorisValidNameError()
Returns an Error if a name is invalid. This deprecated helper is retained for
backwards compatibility; call assertName and catch the thrown GraphQLError
instead because isValidNameError will be removed in v17.
Signature:
isValidNameError(
name: string,
): GraphQLError | undefined;
| Name | Type | Description |
|---|---|---|
| name | string | The GraphQL name to validate. |
| Type | Description |
|---|---|
GraphQLError | undefined | A GraphQLError if the name is invalid; otherwise undefined. |
import { isValidNameError } from 'graphql/utilities';
isValidNameError('User'); // => undefined
const error = isValidNameError('__typename');
error.message; // => 'Name "__typename" must not begin with "__", which is reserved by GraphQL introspection.'Category: Values
Functions
astFromValue()
Produces a GraphQL Value AST given a JavaScript object. Function will match JavaScript/JSON values to GraphQL AST schema format by using suggested GraphQLInputType.
A GraphQL type must be provided, which will be used to interpret different JavaScript values.
| JSON Value | GraphQL Value |
|---|---|
| Object | Input Object |
| Array | List |
| Boolean | Boolean |
| String | String / Enum Value |
| Number | Int / Float |
| Unknown | Enum Value |
| null | NullValue |
Signature:
astFromValue(
value: unknown,
type: GraphQLInputType,
): Maybe<ValueNode>;
| Name | Type | Description |
|---|---|---|
| value | unknown | Runtime value to convert. |
| type | GraphQLInputType | The GraphQL type to inspect. |
| Type | Description |
|---|---|
Maybe<ValueNode> | 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.
Signature:
coerceInputValue(
inputValue: unknown,
type: GraphQLInputType,
onError: (
path: ReadonlyArray<string | number>,
invalidValue: unknown,
error: GraphQLError,
) => void = defaultOnError,
): unknown;
| Name | Type | Default | Description |
|---|---|---|---|
| inputValue | unknown | JavaScript value to coerce. | |
| type | GraphQLInputType | GraphQL input type to coerce the value against. | |
| onError | (
path: ReadonlyArray<string | number>,
invalidValue: unknown,
error: GraphQLError,
) => void | defaultOnError | Callback invoked for each coercion error. |
| Type | Description |
|---|---|
unknown | Coerced value, or undefined if coercion failed and errors were reported. |
// Coerce runtime input values and throw on invalid input by default.
import {
GraphQLInputObjectType,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLString,
} from 'graphql/type';
import { coerceInputValue } from 'graphql/utilities';
const ReviewInput = new GraphQLInputObjectType({
name: 'ReviewInput',
fields: {
stars: { type: new GraphQLNonNull(GraphQLInt) },
tags: { type: new GraphQLList(GraphQLString) },
},
});
coerceInputValue({ stars: '5', tags: ['featured'] }, ReviewInput); // => { stars: 5, tags: ['featured'] }
coerceInputValue({ stars: 'bad' }, ReviewInput); // throws an error// This variant collects coercion errors with a custom onError callback.
import { GraphQLInt, GraphQLNonNull } from 'graphql/type';
import { coerceInputValue } from 'graphql/utilities';
const errors = [];
const value = coerceInputValue(
null,
new GraphQLNonNull(GraphQLInt),
(path, invalidValue, error) => {
errors.push({ path, invalidValue, message: error.message });
},
);
value; // => undefined
errors; // => [ { path: [], invalidValue: null, message: 'Expected non-nullable type "Int!" not to be null.' } ]typeFromAST()
Given a Schema and an AST node describing a type, return a GraphQLType
definition which applies to that type. For example, if provided the parsed
AST node for [User], a GraphQLList instance will be returned, containing
the type called “User” found in the schema. If a type called “User” is not
found in the schema, then undefined will be returned.
Signature:
typeFromAST(
schema: GraphQLSchema,
typeNode: NamedTypeNode,
): GraphQLNamedType | undefined;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| typeNode | NamedTypeNode | The GraphQL type AST node to resolve. |
| Type | Description |
|---|---|
GraphQLNamedType | undefined | The GraphQL type referenced by the AST node, or undefined if it cannot be resolved. |
import { parseType } from 'graphql/language';
import { buildSchema, typeFromAST } from 'graphql/utilities';
const schema = buildSchema(`
type Query {
name: String
}
`);
typeFromAST(schema, parseType('String'))?.toString(); // => 'String'
typeFromAST(schema, parseType('Missing')); // => undefinedResolves a list type AST node against a schema.
Signature:
typeFromAST(
schema: GraphQLSchema,
typeNode: ListTypeNode,
): GraphQLList<any> | undefined;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| typeNode | ListTypeNode | The list type AST node to resolve. |
| Type | Description |
|---|---|
GraphQLList<any> | undefined | The GraphQL list type referenced by the AST node, or undefined if it cannot be resolved. |
import { parseType } from 'graphql/language';
import { buildSchema, typeFromAST } from 'graphql/utilities';
const schema = buildSchema(`
type Query {
tags: [String]
}
`);
typeFromAST(schema, parseType('[String]'))?.toString(); // => '[String]'
typeFromAST(schema, parseType('[Missing]')); // => undefinedResolves a non-null type AST node against a schema.
Signature:
typeFromAST(
schema: GraphQLSchema,
typeNode: NonNullTypeNode,
): GraphQLNonNull<any> | undefined;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| typeNode | NonNullTypeNode | The non-null type AST node to resolve. |
| Type | Description |
|---|---|
GraphQLNonNull<any> | undefined | The GraphQL non-null type referenced by the AST node, or undefined if it cannot be resolved. |
import { parseType } from 'graphql/language';
import { buildSchema, typeFromAST } from 'graphql/utilities';
const schema = buildSchema(`
type Query {
name: String!
}
`);
typeFromAST(schema, parseType('String!'))?.toString(); // => 'String!'
typeFromAST(schema, parseType('[String!]!'))?.toString(); // => '[String!]!'Resolves a type AST node against a schema.
Signature:
typeFromAST(
schema: GraphQLSchema,
typeNode: TypeNode,
): GraphQLType | undefined;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| typeNode | TypeNode | The GraphQL type AST node to resolve. |
| Type | Description |
|---|---|
GraphQLType | undefined | The GraphQL type referenced by the AST node, or undefined if it cannot be resolved. |
import { parseType } from 'graphql/language';
import { buildSchema, typeFromAST } from 'graphql/utilities';
const schema = buildSchema(`
type User {
name: String
}
type Query {
users: [User!]!
}
`);
typeFromAST(schema, parseType('User'))?.toString(); // => 'User'
typeFromAST(schema, parseType('[User!]!'))?.toString(); // => '[User!]!'
typeFromAST(schema, parseType('Missing')); // => undefinedvalueFromAST()
Produces a JavaScript value given a GraphQL Value AST.
A GraphQL type must be provided, which will be used to interpret different GraphQL Value literals.
Returns undefined when the value could not be validly coerced according to
the provided type.
| GraphQL Value | JSON Value |
|---|---|
| Input Object | Object |
| List | Array |
| Boolean | Boolean |
| String | String |
| Int / Float | Number |
| Enum Value | Unknown |
| NullValue | null |
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'Category: 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,
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 },
): GraphQLSchema;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| documentAST | DocumentNode | The parsed GraphQL document AST. |
| options? | { assumeValidSDL?: boolean } | 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()
Enumerations:
BreakingChangeTypeDangerousChangeType
Functions
findBreakingChanges()
Given two schemas, returns an Array containing descriptions of all the types of breaking changes covered by the other functions down below.
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 User {
id: ID!
name: String
}
type Query {
viewer: User
}
`);
const newSchema = buildSchema(`
type User {
id: ID!
}
type Query {
viewer: User
}
`);
const changes = findBreakingChanges(oldSchema, newSchema);
changes[0].type; // => 'FIELD_REMOVED'
changes[0].description; // matches /User.name was removed/findDangerousChanges()
Given two schemas, returns an Array containing descriptions of all the types of potentially dangerous changes covered by the other functions down below.
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[0].type; // => 'VALUE_ADDED_TO_ENUM'
changes[0].description; // matches /EMPIRE was added/Enumerations
BreakingChangeType
Enumeration. Categories of schema changes that may break existing operations.
| Name | Value | Description |
|---|---|---|
TYPE_REMOVED | "TYPE_REMOVED" | Breaking change code for type removed. |
TYPE_CHANGED_KIND | "TYPE_CHANGED_KIND" | Breaking change code for type changed kind. |
TYPE_REMOVED_FROM_UNION | "TYPE_REMOVED_FROM_UNION" | Breaking change code for type removed from union. |
VALUE_REMOVED_FROM_ENUM | "VALUE_REMOVED_FROM_ENUM" | Breaking change code for value removed from enum. |
REQUIRED_INPUT_FIELD_ADDED | "REQUIRED_INPUT_FIELD_ADDED" | Breaking change code for required input field added. |
IMPLEMENTED_INTERFACE_REMOVED | "IMPLEMENTED_INTERFACE_REMOVED" | Breaking change code for implemented interface removed. |
FIELD_REMOVED | "FIELD_REMOVED" | Breaking change code for field removed. |
FIELD_CHANGED_KIND | "FIELD_CHANGED_KIND" | Breaking change code for field changed kind. |
REQUIRED_ARG_ADDED | "REQUIRED_ARG_ADDED" | Breaking change code for required arg added. |
ARG_REMOVED | "ARG_REMOVED" | Breaking change code for arg removed. |
ARG_CHANGED_KIND | "ARG_CHANGED_KIND" | Breaking change code for arg changed kind. |
DIRECTIVE_REMOVED | "DIRECTIVE_REMOVED" | Breaking change code for directive removed. |
DIRECTIVE_ARG_REMOVED | "DIRECTIVE_ARG_REMOVED" | Breaking change code for directive arg removed. |
REQUIRED_DIRECTIVE_ARG_ADDED | "REQUIRED_DIRECTIVE_ARG_ADDED" | Breaking change code for required directive arg added. |
DIRECTIVE_REPEATABLE_REMOVED | "DIRECTIVE_REPEATABLE_REMOVED" | Breaking change code for directive repeatable removed. |
DIRECTIVE_LOCATION_REMOVED | "DIRECTIVE_LOCATION_REMOVED" | Breaking change code for directive location removed. |
DangerousChangeType
Enumeration. Categories of schema changes that may be dangerous for existing operations.
| Name | Value | Description |
|---|---|---|
VALUE_ADDED_TO_ENUM | "VALUE_ADDED_TO_ENUM" | Dangerous change code for value added to enum. |
TYPE_ADDED_TO_UNION | "TYPE_ADDED_TO_UNION" | Dangerous change code for type added to union. |
OPTIONAL_INPUT_FIELD_ADDED | "OPTIONAL_INPUT_FIELD_ADDED" | Dangerous change code for optional input field added. |
OPTIONAL_ARG_ADDED | "OPTIONAL_ARG_ADDED" | Dangerous change code for optional arg added. |
IMPLEMENTED_INTERFACE_ADDED | "IMPLEMENTED_INTERFACE_ADDED" | Dangerous change code for implemented interface added. |
ARG_DEFAULT_VALUE_CHANGE | "ARG_DEFAULT_VALUE_CHANGE" | Dangerous change code for arg default value change. |
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. |
Category: Operations
Functions:
getOperationAST()getOperationRootType()
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'); // => undefinedgetOperationRootType()
Extracts the root type of the operation from the schema. This deprecated
helper is retained for backwards compatibility; call
GraphQLSchema.getRootType instead because getOperationRootType will be
removed in v17.
Signature:
getOperationRootType(
schema: GraphQLSchema,
operation: OperationDefinitionNode | OperationTypeDefinitionNode,
): GraphQLObjectType;
| Name | Type | Description |
|---|---|---|
| schema | GraphQLSchema | GraphQL schema to use. |
| operation | OperationDefinitionNode | OperationTypeDefinitionNode | The operation definition to inspect. |
| Type | Description |
|---|---|
GraphQLObjectType | The resolved operation root type. |
import { buildSchema, getOperationRootType } from 'graphql/utilities';
import { parse } from 'graphql/language';
const schema = buildSchema('type Query { name: String }');
const operation = parse('{ name }').definitions[0];
const rootType = getOperationRootType(schema, operation);
rootType.name; // => 'Query'Category: 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')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 |