@@ -4,11 +4,13 @@ import type { ObjMap } from '../jsutils/ObjMap.js';
44import type { GraphQLError } from '../error/GraphQLError.js' ;
55
66import type {
7+ ConstValueNode ,
78 DocumentNode ,
89 FragmentDefinitionNode ,
910 FragmentSpreadNode ,
1011 OperationDefinitionNode ,
1112 SelectionSetNode ,
13+ VariableDefinitionNode ,
1214 VariableNode ,
1315} from '../language/ast.js' ;
1416import { Kind } from '../language/kinds.js' ;
@@ -34,6 +36,10 @@ interface VariableUsage {
3436 readonly type : Maybe < GraphQLInputType > ;
3537 readonly defaultValue : Maybe < unknown > ;
3638}
39+ interface DefinedVariable {
40+ readonly variableDefinition : VariableDefinitionNode ;
41+ readonly operation : OperationDefinitionNode ;
42+ }
3743
3844/**
3945 * An instance of this class is passed as the "this" context to all validators,
@@ -50,11 +56,16 @@ export class ASTValidationContext {
5056 Array < FragmentDefinitionNode >
5157 > ;
5258
59+ private _variableDefinedOperations :
60+ | ObjMap < ReadonlyArray < DefinedVariable > >
61+ | undefined ;
62+
5363 constructor ( ast : DocumentNode , onError : ( error : GraphQLError ) => void ) {
5464 this . _ast = ast ;
5565 this . _fragments = undefined ;
5666 this . _fragmentSpreads = new Map ( ) ;
5767 this . _recursivelyReferencedFragments = new Map ( ) ;
68+ this . _variableDefinedOperations = undefined ;
5869 this . _onError = onError ;
5970 }
6071
@@ -134,6 +145,28 @@ export class ASTValidationContext {
134145 }
135146 return fragments ;
136147 }
148+
149+ getVariableDefinitions ( node : VariableNode ) : ReadonlyArray < DefinedVariable > {
150+ if ( ! this . _variableDefinedOperations ) {
151+ const variableDefinedOperations : ObjMap < Array < DefinedVariable > > = { } ;
152+ visit ( this . _ast , {
153+ OperationDefinition ( operation ) {
154+ for ( const varDef of operation . variableDefinitions ?? [ ] ) {
155+ if ( ! variableDefinedOperations [ varDef . variable . name . value ] ) {
156+ variableDefinedOperations [ varDef . variable . name . value ] = [ ] ;
157+ }
158+ variableDefinedOperations [ varDef . variable . name . value ] . push ( {
159+ variableDefinition : varDef ,
160+ operation,
161+ } ) ;
162+ }
163+ } ,
164+ } ) ;
165+
166+ this . _variableDefinedOperations = variableDefinedOperations ;
167+ }
168+ return this . _variableDefinedOperations [ node . name . value ] ?? [ ] ;
169+ }
137170}
138171
139172export type ASTValidationRule = ( context : ASTValidationContext ) => ASTVisitor ;
@@ -245,6 +278,10 @@ export class ValidationContext extends ASTValidationContext {
245278 return this . _typeInfo . getInputType ( ) ;
246279 }
247280
281+ getDefaultValue ( ) : Maybe < ConstValueNode > {
282+ return this . _typeInfo . getDefaultValue ( ) as Maybe < ConstValueNode > ;
283+ }
284+
248285 getParentInputType ( ) : Maybe < GraphQLInputType > {
249286 return this . _typeInfo . getParentInputType ( ) ;
250287 }
0 commit comments