| 1 |
from typing import Any, Dict |
| 2 |
|
| 3 |
from ...error import GraphQLError |
| 4 |
from ...language import NameNode, FragmentDefinitionNode, VisitorAction, SKIP |
| 5 |
from . import ASTValidationContext, ASTValidationRule |
| 6 |
|
| 7 |
__all__ = ["UniqueFragmentNamesRule"] |
| 8 |
|
| 9 |
|
| 10 |
class UniqueFragmentNamesRule(ASTValidationRule): |
| 11 |
"""Unique fragment names |
| 12 |
|
| 13 |
A GraphQL document is only valid if all defined fragments have unique names. |
| 14 |
|
| 15 |
See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness |
| 16 |
""" |
| 17 |
|
| 18 |
def __init__(self, context: ASTValidationContext): |
| 19 |
super().__init__(context) |
| 20 |
self.known_fragment_names: Dict[str, NameNode] = {} |
| 21 |
|
| 22 |
@staticmethod |
| 23 |
def enter_operation_definition(*_args: Any) -> VisitorAction: |
| 24 |
return SKIP |
| 25 |
|
| 26 |
def enter_fragment_definition( |
| 27 |
self, node: FragmentDefinitionNode, *_args: Any |
| 28 |
) -> VisitorAction: |
| 29 |
known_fragment_names = self.known_fragment_names |
| 30 |
fragment_name = node.name.value |
| 31 |
if fragment_name in known_fragment_names: |
| 32 |
self.report_error( |
| 33 |
GraphQLError( |
| 34 |
f"There can be only one fragment named '{fragment_name}'.", |
| 35 |
[known_fragment_names[fragment_name], node.name], |
| 36 |
) |
| 37 |
) |
| 38 |
else: |
| 39 |
known_fragment_names[fragment_name] = node.name |
| 40 |
return SKIP |