TExcelTAD
Home › GraphQL › Validation

Validation

Before a single resolver runs, GraphQL checks the whole query against the schema. This validation step is why GraphQL APIs feel so predictable: typos, missing arguments and impossible selections are reported precisely, with line and column, and the server never executes a broken request.

The three phases of a request

graphql() is really three steps, and graphql-js exposes each one:

  1. Parse: turn the query text into an AST (abstract syntax tree). Syntax errors stop here.
  2. Validate: check the AST against the schema with a list of rules.
  3. Execute: call the resolvers and build the result.
js · try it yourself
import { parse, validate, execute, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Planet { name: String!, moons: Int! }
  type Query { planet(name: String!): Planet }
`);

const planets = { Mars: { name: 'Mars', moons: 2 } };
const rootValue = { planet: ({ name }) => planets[name] };

const doc = parse('{ planet(name: "Mars") { name moons } }');
console.log('top-level definitions:', doc.definitions.length);

const errors = validate(schema, doc);
console.log('validation errors:', errors.length);

const result = await execute({ schema, document: doc, rootValue });
console.log(JSON.stringify(result.data));
top-level definitions: 1
validation errors: 0
{"planet":{"name":"Mars","moons":2}}

Servers often cache the parsed and validated document, so a popular query is only checked once.

Syntax errors

A malformed query can't even be parsed. parse throws a GraphQLError with the position:

js · try it yourself
import { parse } from 'graphql';

for (const source of ['{ planet(name: "Mars") { name }', '{ planet(name: Mars") { name } }', 'query { }']) {
  try {
    parse(source);
  } catch (error) {
    console.log(error.message, JSON.stringify(error.locations));
  }
}
Syntax Error: Expected Name, found <EOF>. [{"line":1,"column":32}]
Syntax Error: Unterminated string. [{"line":1,"column":33}]
Syntax Error: Expected Name, found "}". [{"line":1,"column":9}]

Validation errors

A syntactically fine query can still be wrong for this schema. validate returns every problem it finds, not just the first:

js · try it yourself
import { parse, validate, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Planet { name: String!, moons: Int!, neighbours: [Planet!]! }
  type Query { planet(name: String!): Planet }
`);

const doc = parse(`
  query Explore($minMoons: Int) {
    planet { name size }
    other: planet(name: 3) { neighbours }
  }
`);

for (const error of validate(schema, doc)) {
  const { line, column } = error.locations[0];
  console.log(`${line}:${column}  ${error.message}`);
}
3:19  Cannot query field "size" on type "Planet".
3:5  Field "planet" argument "name" of type "String!" is required, but it was not provided.
4:25  String cannot represent a non string value: 3
4:30  Field "neighbours" of type "[Planet!]!" must have a selection of subfields. Did you mean "neighbours { ... }"?
2:17  Variable "$minMoons" is never used in operation "Explore".

The built-in rules

graphql-js implements the spec's rules in specifiedRules. Some of the most useful:

Rule Catches
FieldsOnCorrectTypeRule fields that don't exist on the type
ScalarLeafsRule missing or extra sub-selections
KnownArgumentNamesRule, ProvidedRequiredArgumentsRule unknown and missing arguments
ValuesOfCorrectTypeRule name: 3 for a String
NoUnusedVariablesRule, NoUndefinedVariablesRule variables declared but unused, or used but undeclared
NoUnusedFragmentsRule, KnownFragmentNamesRule fragment mistakes
OverlappingFieldsCanBeMergedRule the same key with different arguments (needs aliases)
UniqueOperationNamesRule two operations with the same name
js · try it yourself
import { specifiedRules } from 'graphql';

console.log(specifiedRules.length, 'rules, for example:');
console.log(specifiedRules.slice(0, 5).map((rule) => rule.name).join(', '));
27 rules, for example:
ExecutableDefinitionsRule, UniqueOperationNamesRule, LoneAnonymousOperationRule, SingleFieldSubscriptionsRule, KnownTypeNamesRule

Your own validation rules

A rule is a function that receives a ValidationContext and returns a visitor: an object whose keys are AST node kinds. Here is a rule that forbids anonymous operations, which helps keep server logs readable:

js · try it yourself
import { parse, validate, specifiedRules, buildSchema, GraphQLError } from 'graphql';

const schema = buildSchema(`type Query { stats: Int }`);

function RequireOperationNameRule(context) {
  return {
    OperationDefinition(node) {
      if (!node.name) {
        context.reportError(
          new GraphQLError('Operations must be named, e.g. "query GetStats { … }".', { nodes: node }),
        );
      }
    },
  };
}

const rules = [...specifiedRules, RequireOperationNameRule];

for (const source of ['{ stats }', 'query GetStats { stats }']) {
  const errors = validate(schema, parse(source), rules);
  console.log(source.padEnd(26), errors.length ? errors[0].message : 'valid');
}
{ stats }                  Operations must be named, e.g. "query GetStats { … }".
query GetStats { stats }   valid

You'll use exactly this technique in the Security lesson to limit query depth.

Note: Validation only checks the shape of a request against the schema. Business rules ("the end date must be after the start date", "only admins can do this") belong in resolvers.

Test yourself

In which order does graphql-js process a request?

  1. Validate, parse, execute
  2. Parse, validate, execute
  3. Execute, validate
  4. Parse, execute, validate

What does validate(schema, document) return?

  1. true or false
  2. The first error only
  3. An array of all validation errors (empty if valid)
  4. The query result

What does a custom validation rule return?

  1. A boolean
  2. A visitor object keyed by AST node kind
  3. A new schema
  4. A resolver