A string containing the version of the GraphQL.js library
export const version: string = ...An object containing the components of the GraphQL.js version string
export const versionInfo: Readonly<{This is the primary entry point function for fulfilling GraphQL operations by parsing, validating, and executing a GraphQL document along side a GraphQL schema.
More sophisticated GraphQL servers, such as those which persist queries, may wish to separate the validation and execution phases to a static time tooling step, and a server runtime step.
Accepts either an object with named arguments, or individual arguments:
schema:
The GraphQL type system to use when validating and executing a query.
source:
A GraphQL language formatted string representing the requested operation.
rootValue:
The value provided as the first argument to resolver functions on the top
level type (e.g. the query object type).
contextValue:
The context value is provided as an argument to resolver functions after
field arguments. It is used to pass shared information useful at any point
during executing this query, for example the currently logged in user and
connections to databases or other services.
variableValues:
A mapping of variable name to runtime value to use for all variables
defined in the requestString.
operationName:
The name of the operation to use if requestString contains multiple
possible operations. Can be omitted if requestString contains only
one operation.
fieldResolver:
A resolver function to use when one is not provided by the schema.
If not provided, the default field resolver is used (which looks for a
value or method on the source value with the field's name).
typeResolver:
A type resolver function to use when none is provided by the schema.
If not provided, the default type resolver is used (which looks for a
__typename
field or alternatively calls the isTypeOf
method).
Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/
type Maybe<T> = null | undefined | TThe graphqlSync function also fulfills GraphQL operations by parsing, validating, and executing a GraphQL document along side a GraphQL schema. However, it guarantees to complete synchronously (or throw an error) assuming that all field resolvers are also synchronous.
export function graphqlSync(args: GraphQLArgs): ExecutionResultSchema Definition
A Schema is created by supplying the root types of each type of operation, query and mutation (optional). A schema definition is then supplied to the validator and executor.
Example:
const MyAppSchema = new GraphQLSchema({query: MyAppQueryRootType,mutation: MyAppMutationRootType,})
Note: When the schema is constructed, by default only the types that are reachable by traversing the root types are included, other types must be explicitly referenced.
Example:
const characterInterface = new GraphQLInterfaceType({name: 'Character',...});const humanType = new GraphQLObjectType({name: 'Human',interfaces: [characterInterface],...});const droidType = new GraphQLObjectType({name: 'Droid',interfaces: [characterInterface],...});const schema = new GraphQLSchema({query: new GraphQLObjectType({name: 'Query',fields: {hero: { type: characterInterface, ... },}}),...// Since this schema references only the `Character` interface it's// necessary to explicitly list the types that implement it if// you want them to be included in the final schema.types: [humanType, droidType],})
Note: If an array of directives
are provided to GraphQLSchema, that will be
the exact list of directives represented and allowed. If directives
is not
provided then a default set of the specified directives (e.g. @include
and
@skip
) will be used. If you wish to provide additional directives to these
specified directives, you must explicitly declare them. Example:
const MyAppSchema = new GraphQLSchema({...directives: specifiedDirectives.concat([ myCustomDirective ]),})
@internal —
interface GraphQLSchemaNormalizedConfig extends GraphQLSchemaConfig {Directives are used by the GraphQL runtime as a way of modifying execution behavior. Type system creators will usually not create these directly.
export class GraphQLDirective {Scalar Type Definition
The leaf values of any request and input values to arguments are Scalars (or Enums) and are defined with a name and a series of functions used to parse input from ast or variables and to ensure validity.
If a type's serialize function returns null
or does not return a value
(i.e. it returns undefined
) then an error will be raised and a null
value will be returned in the response. It is always better to validate
Example:
const OddType = new GraphQLScalarType({name: 'Odd',serialize(value) {if (!Number.isFinite(value)) {throw new Error(`Scalar "Odd" cannot represent "${value}" since it is not a finite number.`,);}if (value % 2 === 0) {throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`);}return value;}});
Object Type Definition
Almost all of the GraphQL types you define will be object types. Object types have a name, but most importantly describe their fields.
Example:
const AddressType = new GraphQLObjectType({name: 'Address',fields: {street: { type: GraphQLString },number: { type: GraphQLInt },formatted: {type: GraphQLString,resolve(obj) {return obj.number + ' ' + obj.street}}}});
When two types need to refer to each other, or a type needs to refer to itself in a field, you can use a function expression (aka a closure or a thunk) to supply the fields lazily.
Example:
const PersonType = new GraphQLObjectType({name: 'Person',fields: () => ({name: { type: GraphQLString },bestFriend: { type: PersonType },})});
Interface Type Definition
When a field can return one of a heterogeneous set of types, a Interface type is used to describe what types are possible, what fields are in common across all types, as well as a function to determine which type is actually used when the field is resolved.
Example:
const EntityType = new GraphQLInterfaceType({name: 'Entity',fields: {name: { type: GraphQLString }}});
Union Type Definition
When a field can return one of a heterogeneous set of types, a Union type is used to describe what types are possible as well as providing a function to determine which type is actually used when the field is resolved.
Example:
const PetType = new GraphQLUnionType({name: 'Pet',types: [ DogType, CatType ],resolveType(value) {if (value instanceof Dog) {return DogType;}if (value instanceof Cat) {return CatType;}}});
Enum Type Definition
Some leaf values of requests and input values are Enums. GraphQL serializes Enum values as strings, however internally Enums can be represented by any kind of type, often integers.
Example:
const RGBType = new GraphQLEnumType({name: 'RGB',values: {RED: { value: 0 },GREEN: { value: 1 },BLUE: { value: 2 }}});
Note: If a value is not provided in a definition, the name of the enum value will be used as its internal value.
Input Object Type Definition
An input object defines a structured collection of fields which may be supplied to a field argument.
Using NonNull
will ensure that a value must be provided by the query
Example:
const GeoPoint = new GraphQLInputObjectType({name: 'GeoPoint',fields: {lat: { type: new GraphQLNonNull(GraphQLFloat) },lon: { type: new GraphQLNonNull(GraphQLFloat) },alt: { type: GraphQLFloat, defaultValue: 0 },}});
List Type Wrapper
A list is a wrapping type which points to another type. Lists are often created within the context of defining the fields of an object type.
Example:
const PersonType = new GraphQLObjectType({name: 'Person',fields: () => ({parents: { type: new GraphQLList(PersonType) },children: { type: new GraphQLList(PersonType) },})})
Non-Null Type Wrapper
A non-null is a wrapping type which points to another type. Non-null types enforce that their values are never null and can ensure an error is raised if this ever occurs during a request. It is useful for fields which you can make a strong guarantee on non-nullability, for example usually the id field of a database row will never be null.
Example:
const RowType = new GraphQLObjectType({name: 'Row',fields: () => ({id: { type: new GraphQLNonNull(GraphQLString) },})})
Note: the enforcement of non-nullability occurs within the executor.
Maximum possible Int value as per GraphQL Spec (32-bit signed integer). n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1
export const GRAPHQL_MAX_INT: 2147483647 = ...Minimum possible Int value as per GraphQL Spec (32-bit signed integer). n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1)
export const GRAPHQL_MIN_INT: -2147483648 = ...The full list of specified directives.
export const specifiedDirectives: readonly GraphQLDirective[] = ...Used to conditionally include fields or fragments.
export const GraphQLIncludeDirective: GraphQLDirective = ...Used to conditionally skip (exclude) fields or fragments.
export const GraphQLSkipDirective: GraphQLDirective = ...Used to declare element of a GraphQL schema as deprecated.
export const GraphQLDeprecatedDirective: GraphQLDirective = ...Used to provide a URL for specifying the behavior of custom scalar definitions.
export const GraphQLSpecifiedByDirective: GraphQLDirective = ...Used to indicate an Input Object is a OneOf Input Object.
export const GraphQLOneOfDirective: GraphQLDirective = ...Constant string used for default reason for a deprecation.
export const DEFAULT_DEPRECATION_REASON: "No longer supported" = ...Note that these are GraphQLField and not GraphQLFieldConfig, so the format for args is different.
export const SchemaMetaFieldDef: GraphQLField<unknown, unknown> = ...Test if the given value is a GraphQL schema.
export function isSchema(schema: unknown): schema is GraphQLSchemaTest if the given value is a GraphQL directive.
export function isDirective(directive: unknown): directive is GraphQLDirectiveThere are predicates for each kind of GraphQL type.
export function isScalarType(type: unknown): type is GraphQLScalarTypeImplements the "Type Validation" sub-sections of the specification's "Type System" section.
Validation runs synchronously, returning an array of encountered errors, or an empty array if no errors were encountered and the Schema is valid.
Utility function which asserts a schema is valid by throwing an error if it is invalid.
export function assertValidSchema(schema: GraphQLSchema): voidUpholds the spec rules about naming.
export function assertName(name: string): stringUpholds the spec rules about naming enum values.
@internal —
These are all of the possible kinds of types.
export type GraphQLType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLType> | GraphQLNonNull<GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLType>>These types may be used as input types for arguments and directives.
export type GraphQLInputType = GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLInputType> | GraphQLNonNull<GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLInputType>>These types may be used as output types as the result of fields.
export type GraphQLOutputType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList<GraphQLOutputType> | GraphQLNonNull<GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList<GraphQLOutputType>>These types may describe types which may be leaf values.
export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumTypeThese types may describe the parent context of a selection set.
export type GraphQLCompositeType = GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionTypeThese types may describe the parent context of a selection set.
export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionTypeThese types wrap and modify other types
export type GraphQLWrappingType = GraphQLList<GraphQLType> | GraphQLNonNull<GraphQLType>These types can all accept null as a value.
export type GraphQLNullableType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLType>These named types do not include modifiers like List or NonNull.
export type GraphQLNamedType = GraphQLNamedInputType | GraphQLNamedOutputTypeUsed while defining GraphQL types to allow for circular references in otherwise immutable type definitions.
export type ThunkReadonlyArray<T> = (() => readonly T[]) | readonly T[]When building a schema from a GraphQL service's introspection result, it might be safe to assume the schema is valid. Set to true to assume the produced schema is valid.
Default: false
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
We've provided these template arguments because this is an open type and you may find them useful.
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Optionally provide a custom type resolver function. If one is not provided,
the default implementation will call isTypeOf
on each implementing
Object type.
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
We've provided these template arguments because this is an open type and you may find them useful.
Serializes an internal value to include in a response.
serialize?: GraphQLScalarSerializer<TExternal>;Parses an externally provided value to use as an input.
parseValue?: GraphQLScalarValueParser<TInternal>;Parses an externally provided literal value to use as an input.
parseLiteral?: GraphQLScalarLiteralParser<TInternal>;Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Optionally provide a custom type resolver function. If one is not provided,
the default implementation will call isTypeOf
on each implementing
Object type.
Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Represents a range of characters represented by a lexical token within a Source.
export class Token {The character offset at which this Node begins.
readonly start: number;The character offset at which this Node ends.
readonly end: number;The 1-indexed line number on which this Token appears.
readonly line: number;The 1-indexed column number at which this Token begins.
readonly column: number;For non-punctuation tokens, represents the interpreted value of the token.
Note: is undefined for punctuation tokens, but typed as string for convenience in the parser.
Tokens exist as nodes in a double-linked-list amongst all tokens including ignored tokens. is always the first node and the last.
readonly prev: Token | null;A representation of source input to GraphQL. The name
and locationOffset
parameters are
optional, but they are useful for clients who store GraphQL documents in source files.
For example, if the GraphQL input starts at line 40 in a file named Foo.graphql
, it might
be useful for name
to be "Foo.graphql"
and location to be { line: 40, column: 1 }
.
The line
and column
properties in locationOffset
are 1-indexed.
Contains a range of UTF-8 character offsets and token references that identify the region of the source from which the AST derived.
export class Location {The character offset at which this Node begins.
readonly start: number;The character offset at which this Node ends.
readonly end: number;Takes a Source and a UTF-8 character offset, and returns the corresponding line and column as a SourceLocation.
export function getLocation(source: Source, position: number): SourceLocationRender a helpful description of the location in the GraphQL Source document.
export function printLocation(location: Location): stringRender a helpful description of the location in the GraphQL Source document.
export function printSourceLocation(source: Source, sourceLocation: SourceLocation): stringGiven a Source object, creates a Lexer for that source. A Lexer is a stateful stream generator in that every time it is advanced, it returns the next token in the Source. Assuming the source lexes, the final Token emitted by the lexer will be of kind EOF, after which the lexer will repeatedly return the same EOF token whenever called.
export class Lexer {The (1-indexed) line containing the current token.
line: number;The character offset at which the current line begins.
lineStart: number;Looks ahead and returns the next non-ignored token, but does not change the state of Lexer.
lookahead(): Token;An exported enum describing the different kinds of tokens that the lexer emits.
export enum TokenKind { }Given a GraphQL source, parses it into a Document. Throws GraphQLError if a syntax error is encountered.
export function parse(source: string | Source, options?: ParseOptions | undefined): DocumentNodeGiven a string containing a GraphQL value (ex. [42]
), parse the AST for
that value.
Throws GraphQLError if a syntax error is encountered.
This is useful within tools that operate upon GraphQL Values directly and in isolation of complete GraphQL documents.
Consider providing the results to the utility function: valueFromAST().
Similar to parseValue(), but raises a parse error if it encounters a variable. The return type will be a constant value.
export function parseConstValue(source: string | Source, options?: ParseOptions | undefined): ConstValueNodeGiven a string containing a GraphQL Type (ex. [Int!]
), parse the AST for
that type.
Throws GraphQLError if a syntax error is encountered.
This is useful within tools that operate upon GraphQL Types directly and in isolation of complete GraphQL documents.
Consider providing the results to the utility function: typeFromAST().
Converts an AST into a string, using one set of reasonable formatting rules.
export function print(ast: ASTNode): stringvisit() will walk through an AST using a depth-first traversal, calling the visitor's enter function at each node in the traversal, and calling the leave function after visiting that node and all of its child nodes.
By returning different values from the enter and leave functions, the behavior of the visitor can be altered, including skipping over a sub-tree of the AST (by returning false), editing the AST by returning a value or null to remove the value, or to stop the whole traversal by returning BREAK.
When using visit() to edit an AST, the original AST will not be modified, and a new version of the AST with the changes applied will be returned from the visit function.
const editedAST = visit(ast, {enter(node, key, parent, path, ancestors) {//@return — // undefined: no action// false: skip visiting this node// visitor.BREAK: stop visiting altogether// null: delete this node// any value: replace this node with the returned value},leave(node, key, parent, path, ancestors) {//@return — // undefined: no action// false: no action// visitor.BREAK: stop visiting altogether// null: delete this node// any value: replace this node with the returned value}});
Alternatively to providing enter() and leave() functions, a visitor can instead provide functions named the same as the kinds of AST nodes, or enter/leave visitors at a named key, leading to three permutations of the visitor API:
visit(ast, {Kind(node) {// enter the "Kind" node}})
visit(ast, {Kind: {enter(node) {// enter the "Kind" node}leave(node) {// leave the "Kind" node}}})
visit(ast, {enter(node) {// enter any node},leave(node) {// leave any node}})
A reducer is comprised of reducer functions which convert AST nodes into another form.
type ASTReducer<R> = { }Creates a new visitor instance which delegates to many visitors to run in parallel. Each visitor will be visited for each node before moving on.
If a prior visitor edits a node, no following visitors will see that node.
Given a visitor instance, if it is leaving or not, and a node kind, return the function the visitor runtime should call.
@deprecated — Please use getEnterLeaveForKind
instead. Will be removed in v17
Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind.
export function getEnterLeaveForKind(visitor: ASTVisitor, kind: Kind): EnterLeaveVisitor<ASTNode>The set of allowed kind values for AST nodes.
export enum Kind { }The set of allowed directive location values.
export enum DirectiveLocation { }Configuration options to control parser behavior
export interface ParseOptions {By default, the parser creates AST nodes that know the location in the source that they correspond to. This configuration flag disables that behavior for performance or testing.
noLocation?: boolean;Parser CPU and memory usage is linear to the number of tokens in a document however in extreme cases it becomes quadratic due to memory exhaustion. Parsing happens before validation so even invalid queries can burn lots of CPU time and memory. To prevent this you can set a maximum number of tokens allowed within a document.
maxTokens?: number | undefined;@deprecated — will be removed in the v17.0.0
If enabled, the parser will understand and parse variable definitions
contained in a fragment definition. They'll be represented in the
variableDefinitions
field of the FragmentDefinitionNode.
The syntax is identical to normal, query-defined variables. For example:
fragment A($var: Boolean = false) on T { ... }
Represents a location in a Source.
export interface SourceLocation {The enum type representing the token kinds values.
@deprecated — Please use TokenKind
. Will be remove in v17.
The enum type representing the possible kind values of AST nodes.
@deprecated — Please use Kind
. Will be remove in v17.
The enum type representing the directive location values.
@deprecated — Please use DirectiveLocation
. Will be remove in v17.
A visitor is provided to visit, it contains the collection of relevant functions to be called during the visitor's traversal.
export type ASTVisitor = EnterLeaveVisitor<ASTNode> | KindVisitorA visitor is comprised of visit functions, which are called on each node during the visitor's traversal.
export type ASTVisitFn<TVisitedNode extends ASTNode> = (node: TVisitedNode, key: string | number | undefined, parent: ASTNode | readonly ASTNode[] | undefined, path: readonly string | number[], ancestors: readonly ASTNode | readonly ASTNode[][]) => anyA KeyMap describes each the traversable properties of each kind of node.
@deprecated — Please inline it. Will be removed in v17
The list of all possible AST node types.
export type ASTNode = NameNode | DocumentNode | OperationDefinitionNode | VariableDefinitionNode | VariableNode | SelectionSetNode | FieldNode | ArgumentNode | FragmentSpreadNode | InlineFragmentNode | FragmentDefinitionNode | IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ListValueNode | ObjectValueNode | ObjectFieldNode | DirectiveNode | NamedTypeNode | ListTypeNode | NonNullTypeNode | SchemaDefinitionNode | OperationTypeDefinitionNode | ScalarTypeDefinitionNode | ObjectTypeDefinitionNode | FieldDefinitionNode | InputValueDefinitionNode | InterfaceTypeDefinitionNode | UnionTypeDefinitionNode | EnumTypeDefinitionNode | EnumValueDefinitionNode | InputObjectTypeDefinitionNode | DirectiveDefinitionNode | SchemaExtensionNode | ScalarTypeExtensionNode | ObjectTypeExtensionNode | InterfaceTypeExtensionNode | UnionTypeExtensionNode | EnumTypeExtensionNode | InputObjectTypeExtensionNodeUtility type listing all nodes indexed by their kind.
export type ASTKindToNode = { }Document
export interface DocumentNode { }Fragments
export interface FragmentSpreadNode { }@deprecated — variableDefinitions will be removed in v17.0.0
readonly variableDefinitions?: readonly VariableDefinitionNode[];Values
export type ValueNode = VariableNode | IntValueNode | FloatValueNode | StringValueNode | BooleanValueNode | NullValueNode | EnumValueNode | ListValueNode | ObjectValueNodeDirectives
export interface DirectiveNode { }Type System Definition
export type TypeSystemDefinitionNode = SchemaDefinitionNode | TypeDefinitionNode | DirectiveDefinitionNodeType Definition
export type TypeDefinitionNode = ScalarTypeDefinitionNode | ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode | UnionTypeDefinitionNode | EnumTypeDefinitionNode | InputObjectTypeDefinitionNodeDirective Definitions
export interface DirectiveDefinitionNode {Type Extensions
export type TypeExtensionNode = ScalarTypeExtensionNode | ObjectTypeExtensionNode | InterfaceTypeExtensionNode | UnionTypeExtensionNode | EnumTypeExtensionNode | InputObjectTypeExtensionNodeImplements the "Executing requests" section of the GraphQL specification.
Returns either a synchronous ExecutionResult (if all encountered resolvers are synchronous), or a Promise of an ExecutionResult that will eventually be resolved and never rejected.
If the arguments to this function do not result in a legal execution context, a GraphQLError will be thrown immediately explaining the invalid input.
Also implements the "Executing requests" section of the GraphQL specification. However, it guarantees to complete synchronously (or throw an error) assuming that all field resolvers are also synchronous.
export function executeSync(args: ExecutionArgs): ExecutionResultIf a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function while passing along args and context value.
export const defaultFieldResolver: GraphQLFieldResolver<unknown, unknown> = ...If a resolveType function is not given, then a default resolve behavior is used which attempts two strategies:
First, See if the provided value has a __typename
field defined, if so, use
that value as name of the resolved type.
Otherwise, test each possible type for the abstract type by calling isTypeOf for the object being coerced, returning the first type that matches.
Prepares an object map of argument values given a list of argument definitions and list of argument AST nodes.
Note: The returned value is a plain Object with a prototype, since it is exposed to user code. Care should be taken to not pull values from the Object prototype.
Prepares an object map of variableValues of the correct type based on the provided variable definitions and arbitrary input. If the input cannot be parsed to match the variable definitions, a GraphQLError will be thrown.
Note: The returned value is a plain Object with a prototype, since it is exposed to user code. Care should be taken to not pull values from the Object prototype.
Prepares an object map of argument values given a directive definition and a AST node which may contain directives. Optionally also accepts a map of variable values.
If the directive does not exist on the node, returns undefined.
Note: The returned value is a plain Object with a prototype, since it is exposed to user code. Care should be taken to not pull values from the Object prototype.
Implements the "Subscribe" algorithm described in the GraphQL specification.
Returns a Promise which resolves to either an AsyncIterator (if successful) or an ExecutionResult (error). The promise will be rejected if the schema or other arguments to this function are invalid, or if the resolved event stream is not an async iterable.
If the client-provided arguments to this function do not result in a compliant subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no data will be returned.
If the source stream could not be created due to faulty subscription
resolver logic or underlying systems, the promise will resolve to a single
ExecutionResult containing errors
and no data
.
If the operation succeeded, the promise resolves to an AsyncIterator, which yields a stream of ExecutionResults representing the response stream.
Accepts either an object with named arguments, or individual arguments.
Implements the "CreateSourceEventStream" algorithm described in the GraphQL specification, resolving the subscription source event stream.
Returns a Promise which resolves to either an AsyncIterable (if successful) or an ExecutionResult (error). The promise will be rejected if the schema or other arguments to this function are invalid, or if the resolved event stream is not an async iterable.
If the client-provided arguments to this function do not result in a compliant subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no data will be returned.
If the the source stream could not be created due to faulty subscription
resolver logic or underlying systems, the promise will resolve to a single
ExecutionResult containing errors
and no data
.
If the operation succeeded, the promise resolves to the AsyncIterable for the event stream returned by the resolver.
A Source Event Stream represents a sequence of events, each of which triggers a GraphQL execution for that event.
This may be useful when hosting the stateful subscription service in a different process or machine than the stateless GraphQL execution engine, or otherwise separating these two steps. For more on this, see the "Supporting Subscriptions at Scale" information in the GraphQL specification.
@deprecated — will be removed in next major version in favor of named arguments
export function createSourceEventStream(schema: GraphQLSchema, document: DocumentNode, rootValue?: unknown, contextValue?: unknown, variableValues?: Maybe<{The result of GraphQL execution.
errors
is included when any errors occurred as a non-empty array.data
is the result of a successful execution of the query.extensions
is reserved for adding non-standard properties.@deprecated — use ExecutionArgs instead. Will be removed in v17
ExecutionArgs has been broadened to include all properties within SubscriptionArgs. The SubscriptionArgs type is retained for backwards compatibility.
Implements the "Validation" section of the spec.
Validation runs synchronously, returning an array of encountered errors, or an empty array if no errors were encountered and the document is valid.
A list of specific validation rules may be provided. If not provided, the default list of rules defined by the GraphQL specification will be used.
Each validation rules is a function which returns a visitor (see the language/visitor API). Visitor methods are expected to return GraphQLErrors, or Arrays of GraphQLErrors when invalid.
Validate will stop validation after a maxErrors
limit has been reached.
Attackers can send pathologically invalid queries to induce a DoS attack,
so by default maxErrors
set to 100 errors.
Optionally a custom TypeInfo instance may be provided. If not provided, one will be created from the provided schema.
An instance of this class is passed as the "this" context to all validators, allowing access to commonly useful contextual information from within a validation rule.
class ASTValidationContext {This set includes all validation rules defined by the GraphQL spec.
The order of the rules in this list has been adjusted to lead to the most clear output when encountering multiple validation errors.
Technically these aren't part of the spec but they are strongly encouraged validation rules.
export const recommendedRules: readonly typeof MaxIntrospectionDepthRule[] = ...Executable definitions
A GraphQL document is only valid for execution if all definitions are either operation or fragment definitions.
See https://spec.graphql.org/draft/#sec-Executable-Definitions
Fields on correct type
A GraphQL document is only valid if all fields selected are defined by the parent type, or are an allowed meta field such as __typename.
Fragments on composite type
Fragments use a type condition to determine if they apply, since fragments can only be spread into a composite type (object, interface, or union), the type condition must also be a composite type.
See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types
Known argument names
A GraphQL field is only valid if all supplied arguments are defined by that field.
See https://spec.graphql.org/draft/#sec-Argument-Names See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations
Known directives
A GraphQL document is only valid if all @directives
are known by the
schema and legally positioned.
See https://spec.graphql.org/draft/#sec-Directives-Are-Defined
Known fragment names
A GraphQL document is only valid if all ...Fragment
fragment spreads refer
to fragments defined in the same document.
See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined
Known type names
A GraphQL document is only valid if referenced types (specifically variable definitions and fragment conditions) are defined by the type schema.
See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence
Lone anonymous operation
A GraphQL document is only valid if when it contains an anonymous operation (the query short-hand) that it contains only that one operation definition.
See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation
No fragment cycles
The graph of fragment spreads must not form any cycles including spreading itself. Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data.
See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles
No undefined variables
A GraphQL operation is only valid if all variables encountered, both directly and via fragment spreads, are defined by that operation.
See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined
No unused fragments
A GraphQL document is only valid if all fragment definitions are spread within operations, or spread within other fragments spread within operations.
See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used
No unused variables
A GraphQL operation is only valid if all variables defined by an operation are used, either directly or within a spread fragment.
Overlapping fields can be merged
A selection set is only valid if all fields (including spreading any fragments) either correspond to distinct response names or can be merged without ambiguity.
See https://spec.graphql.org/draft/#sec-Field-Selection-Merging
Possible fragment spread
A fragment spread is only valid if the type condition could ever possibly be true: if there is a non-empty intersection of the possible parent types, and possible types which pass the type condition.
Provided required arguments
A field or directive is only valid if all required (non-null without a default value) field arguments have been provided.
Scalar leafs
A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.
Subscriptions must only include a non-introspection field.
A GraphQL subscription is valid only if it contains a single root field and that root field is not an introspection field.
Unique argument names
A GraphQL field or directive is only valid if all supplied arguments are uniquely named.
Unique directive names per location
A GraphQL document is only valid if all non-repeatable directives at a given location are uniquely named.
See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location
Unique fragment names
A GraphQL document is only valid if all defined fragments have unique names.
See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness
Unique input field names
A GraphQL input object value is only valid if all supplied fields are uniquely named.
See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness
Unique operation names
A GraphQL document is only valid if all defined operations have unique names.
See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness
Unique variable names
A GraphQL operation is only valid if all its variables are uniquely named.
Value literals of correct type
A GraphQL document is only valid if all value literals are of the type expected at their position.
See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type
Variables are input types
A GraphQL operation is only valid if all the variables it defines are of input types (scalar, enum, or input object).
See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types
Variables in allowed position
Variable usages must be compatible with the arguments they are passed to.
See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed
Lone Schema definition
A GraphQL document is only valid if it contains only one schema definition.
Unique operation types
A GraphQL document is only valid if it has only one type per operation.
Unique type names
A GraphQL document is only valid if all defined types have unique names.
Unique enum value names
A GraphQL enum type is only valid if all its values are uniquely named.
Unique field definition names
A GraphQL complex type is only valid if all its fields are uniquely named.
Unique argument definition names
A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. A GraphQL Directive is only valid if all its arguments are uniquely named.
Unique directive names
A GraphQL document is only valid if all defined directives have unique names.
Possible type extension
A type extension is only valid if the type is defined and has the same kind.
No deprecated
A GraphQL document is only valid if all selected fields and all used enum values have not been deprecated.
Note: This rule is optional and is not part of the Validation section of the GraphQL Specification. The main purpose of this rule is detection of deprecated usages and not necessarily to forbid their use when querying a service.
Prohibit introspection queries
A GraphQL document is only valid if all fields selected are not fields that return an introspection type.
Note: This rule is optional and is not part of the Validation section of the GraphQL Specification. This rule effectively disables introspection, which does not reflect best practices and should only be done if absolutely necessary.
A GraphQLError describes an Error found during the parse, validate, or execute phases of performing a GraphQL operation. In addition to a message and stack trace, it also includes information about the locations in a GraphQL document and/or execution result that correspond to the Error.
export class GraphQLError extends Error {@deprecated — Please use the GraphQLErrorOptions
constructor overload instead.
An array of { line, column }
locations within the source GraphQL document
which correspond to this error.
Errors during validation often contain multiple locations, for example to point out two things with the same name. Errors during execution include a single location, the field which produced the error.
Enumerable, and appears in the result of JSON.stringify().
An array describing the JSON-path into the execution response which corresponds to this error. Only included for errors during execution.
Enumerable, and appears in the result of JSON.stringify().
An array of GraphQL AST Nodes corresponding to this error.
readonly nodes: readonly ASTNode[] | undefined;The source GraphQL document for the first location of this error.
Note that if this Error represents more than one node, the source may not represent nodes after the first node.
An array of character offsets within the source GraphQL document which correspond to this error.
readonly positions: readonly number[] | undefined;The original error thrown from a field resolver during execution.
readonly originalError: Error | undefined;Produces a GraphQLError representing a syntax error, containing useful descriptive information about the syntax error's position in the source.
export function syntaxError(source: Source, position: number, description: string): GraphQLErrorGiven an arbitrary value, presumably thrown while attempting to execute a GraphQL operation, produce a new GraphQLError aware of the location in the document responsible for the original Error.
export function locatedError(rawOriginalError: unknown, nodes: ASTNode | readonly ASTNode[] | undefined | null, path?: Maybe<readonly string | number[]>): GraphQLErrorPrints a GraphQLError to a string, representing useful location information about the error's position in the source.
@deprecated — Please use error.toString
instead. Will be removed in v17
Given a GraphQLError, format it according to the rules described by the Response Format, Errors section of the GraphQL Specification.
@deprecated — Please use error.toJSON
instead. Will be removed in v17
See: https://spec.graphql.org/draft/#sec-Errors
export interface GraphQLFormattedError {A short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization.
readonly message: string;If an error can be associated to a particular point in the requested GraphQL document, it should contain a list of locations.
readonly locations?: readonly SourceLocation[];If an error can be associated to a particular field in the GraphQL result,
it must contain an entry with the key path
that details the path of
the response field which experienced the error. This allows clients to
identify whether a null result is intentional or caused by a runtime error.
Reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.
readonly extensions?: {Custom extensions
@remarks — Use a unique identifier name for your extension, for example the name of your library or project. Do not use a shortened identifier as this increases the risk of conflicts. We recommend you add at most one extension field, an object which can contain all the values you need.
Produce the GraphQL query recommended for a full schema introspection. Accepts optional IntrospectionOptions.
export function getIntrospectionQuery(options?: IntrospectionOptions): stringReturns 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.
export function getOperationAST(documentAST: DocumentNode, operationName?: Maybe<string>): Maybe<OperationDefinitionNode>Extracts the root type of the operation from the schema.
@deprecated — Please use GraphQLSchema.getRootType
instead. Will be removed in v17
Build an IntrospectionQuery from a GraphQLSchema
IntrospectionQuery is useful for utilities that care about type and field relationships, but do not need to traverse through those relationships.
This is the inverse of buildClientSchema. The primary use case is outside of the server context, for instance when doing schema comparisons.
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.
This takes the ast of a schema document produced by the parse function in src/language/parser.js.
If no schema definition is provided, then it will look for types named Query, Mutation and Subscription.
Given that AST it constructs a GraphQLSchema. The resulting schema has no resolve methods, so execution will use default resolvers.
A helper function to build a GraphQLSchema directly from a source document.
export function buildSchema(source: string | Source, options?: BuildSchemaOptions & ParseOptions): GraphQLSchemaProduces 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.
Set to true to assume the SDL is valid.
Default: false
Sort GraphQLSchema.
This function returns a sorted copy of the given GraphQLSchema.
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.
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 |
Produces a JavaScript value given a GraphQL Value AST.
Unlike valueFromAST()
, no type is provided. The resulting JavaScript value
will reflect the provided GraphQL value AST.
GraphQL Value | JavaScript Value |
---|---|
Input Object | Object |
List | Array |
Boolean | Boolean |
String / Enum | String |
Int / Float | Number |
Null | null |
Produces a GraphQL Value AST given a JavaScript object. Function will match JavaScript/JSON values to GraphQL AST schema format by using suggested GraphQLInputType. For example:
astFromValue("value", GraphQLString)
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 |
TypeInfo is a utility class which, given a GraphQL schema, can keep track
of the current field and type definitions at any point in a GraphQL document
AST during a recursive descent by calling enter(node)
and leave(node)
.
Creates a new visitor instance which maintains a provided TypeInfo instance along with visiting visitor.
export function visitWithTypeInfo(typeInfo: TypeInfo, visitor: ASTVisitor): ASTVisitorCoerces a JavaScript value given a GraphQL Input Type.
export function coerceInputValue(inputValue: unknown, type: GraphQLInputType, onError?: OnErrorCB): unknownProvided 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.
export function concatAST(documents: readonly DocumentNode[]): DocumentNodeseparateOperations 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.
export function separateOperations(documentAST: DocumentNode): ObjMap<DocumentNode>Strips characters that are not significant to the validity or execution of a GraphQL document:
Note: It is required to have a delimiter character between neighboring non-punctuator tokens and this function always uses single space as delimiter.
It is guaranteed that both input and output documents if parsed would result in the exact same AST except for nodes location.
Warning: It is guaranteed that this function will always produce stable results. However, it's not guaranteed that it will stay the same between different releases due to bugfixes or changes in the GraphQL specification.
Query example:
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}}}
SDL example:
""" Type description """ type Foo { """ Field description """ bar: String }
Becomes:
"""Type description""" type Foo{"""Field description""" bar:String}
Provided two types, return true if the types are equal (invariant).
export function isEqualType(typeA: GraphQLType, typeB: GraphQLType): booleanProvided a type and a super type, return true if the first type is either equal or a subset of the second super type (covariant).
export function isTypeSubTypeOf(schema: GraphQLSchema, maybeSubType: GraphQLType, superType: GraphQLType): booleanProvided 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.
Upholds the spec rules about naming.
@deprecated — Please use assertName
instead. Will be removed in v17
Returns an Error if a name is invalid.
@deprecated — Please use assertName
instead. Will be removed in v17
Given two schemas, returns an Array containing descriptions of all the types of breaking changes covered by the other functions down below.
export function findBreakingChanges(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): BreakingChange[]Given two schemas, returns an Array containing descriptions of all the types of potentially dangerous changes covered by the other functions down below.
export function findDangerousChanges(oldSchema: GraphQLSchema, newSchema: GraphQLSchema): DangerousChange[]Whether to include descriptions in the introspection result. Default: true
descriptions?: boolean;Whether to include specifiedByURL
in the introspection result.
Default: false
Whether to include isRepeatable
flag on directives.
Default: false
Whether to include description
field on schema.
Default: false
Whether target GraphQL server support deprecation of input values. Default: false
inputValueDeprecation?: boolean;Whether target GraphQL server supports @oneOf
input objects.
Default: false
Set to true to assume the SDL is valid.
Default: false
Wrapper type that contains DocumentNode and types that can be deduced from it.
export interface TypedQueryDocumentNode<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
__ensureTypesOfVariablesAndResultMatching?: (variables: TRequestVariables) => TResponseData;