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