| 1 |
from typing import Any, List |
| 2 |
|
| 3 |
from ...error import GraphQLError |
| 4 |
from ...language import ( |
| 5 |
FragmentDefinitionNode, |
| 6 |
OperationDefinitionNode, |
| 7 |
VisitorAction, |
| 8 |
SKIP, |
| 9 |
) |
| 10 |
from . import ASTValidationContext, ASTValidationRule |
| 11 |
|
| 12 |
__all__ = ["NoUnusedFragmentsRule"] |
| 13 |
|
| 14 |
|
| 15 |
class NoUnusedFragmentsRule(ASTValidationRule): |
| 16 |
"""No unused fragments |
| 17 |
|
| 18 |
A GraphQL document is only valid if all fragment definitions are spread within |
| 19 |
operations, or spread within other fragments spread within operations. |
| 20 |
|
| 21 |
See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used |
| 22 |
""" |
| 23 |
|
| 24 |
def __init__(self, context: ASTValidationContext): |
| 25 |
super().__init__(context) |
| 26 |
self.operation_defs: List[OperationDefinitionNode] = [] |
| 27 |
self.fragment_defs: List[FragmentDefinitionNode] = [] |
| 28 |
|
| 29 |
def enter_operation_definition( |
| 30 |
self, node: OperationDefinitionNode, *_args: Any |
| 31 |
) -> VisitorAction: |
| 32 |
self.operation_defs.append(node) |
| 33 |
return SKIP |
| 34 |
|
| 35 |
def enter_fragment_definition( |
| 36 |
self, node: FragmentDefinitionNode, *_args: Any |
| 37 |
) -> VisitorAction: |
| 38 |
self.fragment_defs.append(node) |
| 39 |
return SKIP |
| 40 |
|
| 41 |
def leave_document(self, *_args: Any) -> None: |
| 42 |
fragment_names_used = set() |
| 43 |
get_fragments = self.context.get_recursively_referenced_fragments |
| 44 |
for operation in self.operation_defs: |
| 45 |
for fragment in get_fragments(operation): |
| 46 |
fragment_names_used.add(fragment.name.value) |
| 47 |
|
| 48 |
for fragment_def in self.fragment_defs: |
| 49 |
frag_name = fragment_def.name.value |
| 50 |
if frag_name not in fragment_names_used: |
| 51 |
self.report_error( |
| 52 |
GraphQLError(f"Fragment '{frag_name}' is never used.", fragment_def) |
| 53 |
) |