UniqueVariableNames.js.flow 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. export function duplicateVariableMessage(variableName: string): string {
  7. return `There can be only one variable named "${variableName}".`;
  8. }
  9. /**
  10. * Unique variable names
  11. *
  12. * A GraphQL operation is only valid if all its variables are uniquely named.
  13. */
  14. export function UniqueVariableNames(context: ASTValidationContext): ASTVisitor {
  15. let knownVariableNames = Object.create(null);
  16. return {
  17. OperationDefinition() {
  18. knownVariableNames = Object.create(null);
  19. },
  20. VariableDefinition(node: VariableDefinitionNode) {
  21. const variableName = node.variable.name.value;
  22. if (knownVariableNames[variableName]) {
  23. context.reportError(
  24. new GraphQLError(duplicateVariableMessage(variableName), [
  25. knownVariableNames[variableName],
  26. node.variable.name,
  27. ]),
  28. );
  29. } else {
  30. knownVariableNames[variableName] = node.variable.name;
  31. }
  32. },
  33. };
  34. }