| 1 |
from typing import Any, Dict |
| 2 |
|
| 3 |
from ...error import GraphQLError |
| 4 |
from ...language import DirectiveDefinitionNode, NameNode, VisitorAction, SKIP |
| 5 |
from . import SDLValidationContext, SDLValidationRule |
| 6 |
|
| 7 |
__all__ = ["UniqueDirectiveNamesRule"] |
| 8 |
|
| 9 |
|
| 10 |
class UniqueDirectiveNamesRule(SDLValidationRule): |
| 11 |
"""Unique directive names |
| 12 |
|
| 13 |
A GraphQL document is only valid if all defined directives have unique names. |
| 14 |
""" |
| 15 |
|
| 16 |
def __init__(self, context: SDLValidationContext): |
| 17 |
super().__init__(context) |
| 18 |
self.known_directive_names: Dict[str, NameNode] = {} |
| 19 |
self.schema = context.schema |
| 20 |
|
| 21 |
def enter_directive_definition( |
| 22 |
self, node: DirectiveDefinitionNode, *_args: Any |
| 23 |
) -> VisitorAction: |
| 24 |
directive_name = node.name.value |
| 25 |
|
| 26 |
if self.schema and self.schema.get_directive(directive_name): |
| 27 |
self.report_error( |
| 28 |
GraphQLError( |
| 29 |
f"Directive '@{directive_name}' already exists in the schema." |
| 30 |
" It cannot be redefined.", |
| 31 |
node.name, |
| 32 |
) |
| 33 |
) |
| 34 |
else: |
| 35 |
if directive_name in self.known_directive_names: |
| 36 |
self.report_error( |
| 37 |
GraphQLError( |
| 38 |
f"There can be only one directive named '@{directive_name}'.", |
| 39 |
[self.known_directive_names[directive_name], node.name], |
| 40 |
) |
| 41 |
) |
| 42 |
else: |
| 43 |
self.known_directive_names[directive_name] = node.name |
| 44 |
return SKIP |
| 45 |
|
| 46 |
return None |