Validating Queries and Schema
1. Understanding Validation Rules
| Rule | Detail |
|---|---|
| Spec rules | ~30 standard rules in graphql-js |
| Phase | After parse, before execute |
| Failure | Aborts execution; returns errors |
2. Validating Query Syntax
| Failure | Code |
|---|---|
| Parse error | GRAPHQL_PARSE_FAILED |
| Validation error | GRAPHQL_VALIDATION_FAILED |
| No execution | data is null/absent |
3. Validating Field Selection
| Rule | Detail |
|---|---|
| Field exists | Must be defined on parent type |
| Selection set required | For object/union/interface |
| No selection set | For scalars/enums |
| Compatible nesting | Sub-selection valid for return type |
4. Validating Arguments
| Rule | Detail |
|---|---|
| Known arg names | Match field definition |
| Required args supplied | Non-null without default |
| Type coercion | Literal/variable type compatible |
| Unique arg names | No duplicates per field |
5. Validating Fragments
| Rule | Detail |
|---|---|
| Type exists | Type condition must be defined |
| No cycles | Fragments cannot recurse |
| Spread compatibility | Possible types overlap |
| All used | Defined fragments must be referenced |
6. Validating Variables
| Rule | Detail |
|---|---|
| Unique names | Per operation |
| Input types only | Cannot be object/interface/union |
| All defined used | Cannot declare unused variable |
| Type compatible with arg | Including non-null relationship |
7. Validating Directives
| Rule | Detail |
|---|---|
| Known directive | Defined in schema |
| Allowed location | Matches declaration |
| Args valid | Required args present, types match |
| Unique per location | Unless repeatable |
8. Creating Custom Validation Rules
Example: Depth limit
import depthLimit from "graphql-depth-limit";
import { createComplexityLimitRule } from "graphql-validation-complexity";
const server = new ApolloServer({
schema,
validationRules: [depthLimit(7), createComplexityLimitRule(1000)]
});
9. Disabling Validation Rules
| Use Case | Risk |
|---|---|
| Disable NoUnusedVariables | Generated queries with optional vars |
| Custom rule subset | Skip safety; usually not advised |