uniqueFragmentNamesRule function

Visitor uniqueFragmentNamesRule(
  1. SDLValidationCtx ctx
)

Unique fragment names

A GraphQL document is only valid if all defined fragments have unique names.

See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness

Implementation

Visitor uniqueFragmentNamesRule(
  SDLValidationCtx ctx, // ASTValidationContext
) {
  final fragments = <String, FragmentDefinitionNode>{};

  return TypedVisitor()
    ..add<OperationDefinitionNode>((_) => VisitBehavior.skipTree)
    ..add<FragmentDefinitionNode>((node) {
      final name = node.name.value;
      final prev = fragments[name];
      if (prev != null) {
        ctx.reportError(GraphQLError(
          'There can be only one fragment named "$name".',
          locations: [
            GraphQLErrorLocation.fromSourceLocation(prev.name.span!.start),
            GraphQLErrorLocation.fromSourceLocation(node.name.span!.start),
          ],
          extensions: _uniqueFragmentNamesSpec.extensions(),
        ));
      } else {
        fragments[name] = node;
      }
      return VisitBehavior.skipTree;
    });
}