UniqueVariableNamesRule.js.flow 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // @flow strict
  2. import { GraphQLError } from '../../error/GraphQLError';
  3. import type { ASTVisitor } from '../../language/visitor';
  4. import type { VariableDefinitionNode } from '../../language/ast';
  5. import type { ASTValidationContext } from '../ValidationContext';
  6. /**
  7. * Unique variable names
  8. *
  9. * A GraphQL operation is only valid if all its variables are uniquely named.
  10. */
  11. export function UniqueVariableNamesRule(
  12. context: ASTValidationContext,
  13. ): ASTVisitor {
  14. let knownVariableNames = Object.create(null);
  15. return {
  16. OperationDefinition() {
  17. knownVariableNames = Object.create(null);
  18. },
  19. VariableDefinition(node: VariableDefinitionNode) {
  20. const variableName = node.variable.name.value;
  21. if (knownVariableNames[variableName]) {
  22. context.reportError(
  23. new GraphQLError(
  24. `There can be only one variable named "$${variableName}".`,
  25. [knownVariableNames[variableName], node.variable.name],
  26. ),
  27. );
  28. } else {
  29. knownVariableNames[variableName] = node.variable.name;
  30. }
  31. },
  32. };
  33. }