v17 APIgraphql/validation

graphql/validation

The graphql/validation entry point validates parsed GraphQL documents against a schema. It exports the default rule lists, the validation context, and every specified and GraphQL.js-provided validation rule.

import { validate, specifiedRules } from 'graphql/validation';

The same exports are also available from the root graphql entry point.

Contents

const errors = validate(schema, document, specifiedRules, {
  maxErrors: 25,
  hideSuggestions: true,
});

Descriptions are no longer visited during validation because descriptions do not affect GraphQL validity.

Core Validation Exports

ExportKindDescription
validate() Changed in v17FunctionSynchronously validates a document and returns an array of GraphQLError values. In v17, pass options as the fourth argument; the v16 custom TypeInfo argument was removed.
ValidationContext Changed in v17ClassContext passed to executable validation rules.
ValidationRuleTypeFunction type for executable validation rules.
specifiedRules Changed in v17ArrayAll executable validation rules required by the GraphQL specification and supported proposals.
recommendedRulesArrayGraphQL.js recommended rules that are not part of the core specified rule list, including MaxIntrospectionDepthRule.
const errors = validate(schema, parse(source));
 
if (errors.length > 0) {
  return { errors };
}

Executable Validation Rule Exports

ExportDescription
ExecutableDefinitionsRuleExecutable documents may contain only operations and fragments.
FieldsOnCorrectTypeRuleSelected fields must exist on the parent type.
FragmentsOnCompositeTypesRuleFragments may condition only on composite types.
KnownArgumentNamesRuleField and directive arguments must be defined.
KnownDirectivesRuleDirectives must be defined and used in valid locations.
KnownFragmentNamesRuleFragment spreads must refer to defined fragments.
KnownOperationTypesRule New in v17Operation types must be supported by the schema.
KnownTypeNamesRuleReferenced types must exist in the schema.
LoneAnonymousOperationRuleAnonymous operations must be the only operation in a document.
NoFragmentCyclesRuleFragments must not form cycles.
NoUndefinedVariablesRuleUsed variables must be defined by the operation or fragment arguments.
NoUnusedFragmentsRuleFragment definitions must be used.
NoUnusedVariablesRuleVariable definitions must be used.
OverlappingFieldsCanBeMergedRuleFields with the same response name must be merge-compatible.
PossibleFragmentSpreadsRuleFragment spreads must be possible for the parent and condition types.
ProvidedRequiredArgumentsRuleRequired arguments must be provided.
ScalarLeafsRuleLeaf fields must not have selections and composite fields must have selections.
SingleFieldSubscriptionsRuleSubscriptions must select exactly one root field.
UniqueArgumentNamesRuleArguments at one location must be unique.
UniqueDirectivesPerLocationRuleNon-repeatable directives must not repeat at one location.
UniqueFragmentNamesRuleFragment names must be unique.
UniqueInputFieldNamesRuleInput object field names must be unique.
UniqueOperationNamesRuleOperation names must be unique.
UniqueVariableNamesRuleVariable names in an operation or fragment must be unique.
ValuesOfCorrectTypeRuleLiteral values must be valid for their expected input type.
VariablesAreInputTypesRuleVariables must use input types.
VariablesInAllowedPositionRuleVariable usages must be valid for their location.

Incremental Delivery Rule Exports

These rules are new in v17 and validate @defer / @stream usage.

ExportDescription
DeferStreamDirectiveLabelRule New in v17@defer and @stream labels must be unique where required.
DeferStreamDirectiveOnRootFieldRule New in v17@defer and @stream cannot be used on invalid root fields.
DeferStreamDirectiveOnValidOperationsRule New in v17@defer and @stream must appear only on operations that can support them.
StreamDirectiveOnListFieldRule New in v17@stream must be used on list fields.

SDL Validation Rule Exports

ExportDescription
LoneSchemaDefinitionRuleA schema document may define the schema only once.
UniqueOperationTypesRuleEach operation root type may be defined only once.
UniqueTypeNamesRuleType names must be unique.
UniqueEnumValueNamesRuleEnum value names must be unique within an enum.
UniqueFieldDefinitionNamesRuleField names must be unique within object and interface types.
UniqueArgumentDefinitionNamesRuleArgument names must be unique within a field or directive definition.
UniqueDirectiveNamesRuleDirective definition names must be unique.
PossibleTypeExtensionsRuleType extensions must extend existing or well-formed types of the right kind.

Optional Rule Exports

ExportDescription
MaxIntrospectionDepthRuleLimits nested introspection depth. Included in recommendedRules.
NoDeprecatedCustomRuleReports usage of deprecated fields, arguments, input fields, and enum values.
NoSchemaIntrospectionCustomRuleDisallows schema introspection fields.

Custom Rules

Custom rules are functions that receive a ValidationContext and return an AST visitor.

import { GraphQLError, specifiedRules, validate } from 'graphql';
 
function NoViewerFieldRule(context) {
  return {
    Field(node) {
      if (node.name.value === 'viewer') {
        context.reportError(
          new GraphQLError('The viewer field is disabled.', { nodes: node }),
        );
      }
    },
  };
}
 
const errors = validate(schema, document, [
  ...specifiedRules,
  NoViewerFieldRule,
]);