| 1 |
from typing import Any, List, Set |
| 2 |
|
| 3 |
from ...error import GraphQLError |
| 4 |
from ...language import OperationDefinitionNode, VariableDefinitionNode |
| 5 |
from . import ValidationContext, ValidationRule |
| 6 |
|
| 7 |
__all__ = ["NoUnusedVariablesRule"] |
| 8 |
|
| 9 |
|
| 10 |
class NoUnusedVariablesRule(ValidationRule): |
| 11 |
"""No unused variables |
| 12 |
|
| 13 |
A GraphQL operation is only valid if all variables defined by an operation are used, |
| 14 |
either directly or within a spread fragment. |
| 15 |
|
| 16 |
See https://spec.graphql.org/draft/#sec-All-Variables-Used |
| 17 |
""" |
| 18 |
|
| 19 |
def __init__(self, context: ValidationContext): |
| 20 |
super().__init__(context) |
| 21 |
self.variable_defs: List[VariableDefinitionNode] = [] |
| 22 |
|
| 23 |
def enter_operation_definition(self, *_args: Any) -> None: |
| 24 |
self.variable_defs.clear() |
| 25 |
|
| 26 |
def leave_operation_definition( |
| 27 |
self, operation: OperationDefinitionNode, *_args: Any |
| 28 |
) -> None: |
| 29 |
variable_name_used: Set[str] = set() |
| 30 |
usages = self.context.get_recursive_variable_usages(operation) |
| 31 |
|
| 32 |
for usage in usages: |
| 33 |
variable_name_used.add(usage.node.name.value) |
| 34 |
|
| 35 |
for variable_def in self.variable_defs: |
| 36 |
variable_name = variable_def.variable.name.value |
| 37 |
if variable_name not in variable_name_used: |
| 38 |
self.report_error( |
| 39 |
GraphQLError( |
| 40 |
( |
| 41 |
f"Variable '${variable_name}' is never used" |
| 42 |
f" in operation '{operation.name.value}'." |
| 43 |
if operation.name |
| 44 |
else f"Variable '${variable_name}' is never used." |
| 45 |
), |
| 46 |
variable_def, |
| 47 |
) |
| 48 |
) |
| 49 |
|
| 50 |
def enter_variable_definition( |
| 51 |
self, definition: VariableDefinitionNode, *_args: Any |
| 52 |
) -> None: |
| 53 |
self.variable_defs.append(definition) |