UniqueFragmentNames.js.flow 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // @flow strict
  2. import { GraphQLError } from '../../error/GraphQLError';
  3. import { type ASTVisitor } from '../../language/visitor';
  4. import { type ASTValidationContext } from '../ValidationContext';
  5. export function duplicateFragmentNameMessage(fragName: string): string {
  6. return `There can be only one fragment named "${fragName}".`;
  7. }
  8. /**
  9. * Unique fragment names
  10. *
  11. * A GraphQL document is only valid if all defined fragments have unique names.
  12. */
  13. export function UniqueFragmentNames(context: ASTValidationContext): ASTVisitor {
  14. const knownFragmentNames = Object.create(null);
  15. return {
  16. OperationDefinition: () => false,
  17. FragmentDefinition(node) {
  18. const fragmentName = node.name.value;
  19. if (knownFragmentNames[fragmentName]) {
  20. context.reportError(
  21. new GraphQLError(duplicateFragmentNameMessage(fragmentName), [
  22. knownFragmentNames[fragmentName],
  23. node.name,
  24. ]),
  25. );
  26. } else {
  27. knownFragmentNames[fragmentName] = node.name;
  28. }
  29. return false;
  30. },
  31. };
  32. }