Catch invalid operations early
Check client queries during development or CI before sending them to a server.
GraphQL · Function
GraphQL validates a parsed operation against the schema before execution. Invalid documents produce request errors and do not begin field execution.
In GraphQL.js, validate checks a parsed document against a schema before execution. It returns validation errors; when the document is invalid, execution does not begin and the server reports a request error instead of partial data.
validate(schema, documentAST, rules?)| Name | Type | Description |
|---|---|---|
schema | GraphQLSchema | The GraphQL schema used to validate the document. |
documentAST | DocumentNode | The parsed GraphQL document to check. |
rules | ValidationRule[] | Optional validation rules; the standard rules are used when omitted. |
A list of validation errors; an empty list indicates that the document is valid.
import { buildSchema, parse, validate } from "graphql";
const schema = buildSchema(`
type Query { user: User }
type User { id: ID!, name: String! }
`);
const document = parse(`query { user { id email } }`);
const errors = validate(schema, document);
console.log(errors.map(({ message }) => message));Parses a query, validates it against a schema, and prints the validation messages.
Check client queries during development or CI before sending them to a server.
Reject malformed or schema-incompatible requests at the API boundary.
Verify that fragments and nested selections conform to the schema.
The document is parsed first, then validated against the schema. Validation checks that the operation is valid for the API before execution starts.
Follow-up: What does a validation failure return? It produces a request error describing the problem, and field execution does not start.
A queried field must exist on the relevant type. GraphQL therefore catches references to unknown fields during validation rather than waiting for resolver execution.
Follow-up: How would you prevent a missing-field error? Use the schema or introspection information to select only fields defined on the target type.
Fields returning an object, interface, or union need a selection set describing the fields to retrieve. Scalar and enum fields are leaf values and do not require nested selections.
Follow-up: Why is this useful? It makes the requested response shape explicit and lets the schema validate that shape before any resolver runs.
parseGraphQLSchemaDocumentNodevalidation rulesexecutionfragmentsselection set