1
+ import { groupBy } from '../../jsutils/groupBy' ;
2
+
1
3
import { GraphQLError } from '../../error/GraphQLError' ;
2
4
3
5
import type { ASTVisitor } from '../../language/visitor' ;
4
- import type { VariableDefinitionNode } from '../../language/ast' ;
5
6
6
7
import type { ASTValidationContext } from '../ValidationContext' ;
7
8
@@ -13,22 +14,25 @@ import type { ASTValidationContext } from '../ValidationContext';
13
14
export function UniqueVariableNamesRule (
14
15
context : ASTValidationContext ,
15
16
) : ASTVisitor {
16
- let knownVariableNames = Object . create ( null ) ;
17
17
return {
18
- OperationDefinition ( ) {
19
- knownVariableNames = Object . create ( null ) ;
20
- } ,
21
- VariableDefinition ( node : VariableDefinitionNode ) {
22
- const variableName = node . variable . name . value ;
23
- if ( knownVariableNames [ variableName ] ) {
24
- context . reportError (
25
- new GraphQLError (
26
- `There can be only one variable named "$${ variableName } ".` ,
27
- [ knownVariableNames [ variableName ] , node . variable . name ] ,
28
- ) ,
29
- ) ;
30
- } else {
31
- knownVariableNames [ variableName ] = node . variable . name ;
18
+ OperationDefinition ( operationNode ) {
19
+ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
20
+ const variableDefinitions = operationNode . variableDefinitions ?? [ ] ;
21
+
22
+ const seenVariableDefinitions = groupBy (
23
+ variableDefinitions ,
24
+ ( node ) => node . variable . name . value ,
25
+ ) ;
26
+
27
+ for ( const [ variableName , variableNodes ] of seenVariableDefinitions ) {
28
+ if ( variableNodes . length > 1 ) {
29
+ context . reportError (
30
+ new GraphQLError (
31
+ `There can be only one variable named "$${ variableName } ".` ,
32
+ variableNodes . map ( ( node ) => node . variable . name ) ,
33
+ ) ,
34
+ ) ;
35
+ }
32
36
}
33
37
} ,
34
38
} ;
0 commit comments