UniqueFragmentNamesRule.js.flow 948 B

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