Validating Queries and Schema

1. Understanding Validation Rules

RuleDetail
Spec rules~30 standard rules in graphql-js
PhaseAfter parse, before execute
FailureAborts execution; returns errors

2. Validating Query Syntax

FailureCode
Parse errorGRAPHQL_PARSE_FAILED
Validation errorGRAPHQL_VALIDATION_FAILED
No executiondata is null/absent

3. Validating Field Selection

RuleDetail
Field existsMust be defined on parent type
Selection set requiredFor object/union/interface
No selection setFor scalars/enums
Compatible nestingSub-selection valid for return type

4. Validating Arguments

RuleDetail
Known arg namesMatch field definition
Required args suppliedNon-null without default
Type coercionLiteral/variable type compatible
Unique arg namesNo duplicates per field

5. Validating Fragments

RuleDetail
Type existsType condition must be defined
No cyclesFragments cannot recurse
Spread compatibilityPossible types overlap
All usedDefined fragments must be referenced

6. Validating Variables

RuleDetail
Unique namesPer operation
Input types onlyCannot be object/interface/union
All defined usedCannot declare unused variable
Type compatible with argIncluding non-null relationship

7. Validating Directives

RuleDetail
Known directiveDefined in schema
Allowed locationMatches declaration
Args validRequired args present, types match
Unique per locationUnless 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 CaseRisk
Disable NoUnusedVariablesGenerated queries with optional vars
Custom rule subsetSkip safety; usually not advised

10. Handling Validation Errors

Example: Validation error response

{
  "errors": [{
    "message": "Cannot query field \"foo\" on type \"User\".",
    "locations": [{ "line": 3, "column": 5 }],
    "extensions": { "code": "GRAPHQL_VALIDATION_FAILED" }
  }]
}