| 1 |
from typing import Any |
| 2 |
|
| 3 |
from ...error import GraphQLError |
| 4 |
from ...language import FieldNode |
| 5 |
from ...type import get_named_type, is_leaf_type |
| 6 |
from . import ValidationRule |
| 7 |
|
| 8 |
__all__ = ["ScalarLeafsRule"] |
| 9 |
|
| 10 |
|
| 11 |
class ScalarLeafsRule(ValidationRule): |
| 12 |
"""Scalar leafs |
| 13 |
|
| 14 |
A GraphQL document is valid only if all leaf fields (fields without sub selections) |
| 15 |
are of scalar or enum types. |
| 16 |
""" |
| 17 |
|
| 18 |
def enter_field(self, node: FieldNode, *_args: Any) -> None: |
| 19 |
type_ = self.context.get_type() |
| 20 |
if type_: |
| 21 |
selection_set = node.selection_set |
| 22 |
if is_leaf_type(get_named_type(type_)): |
| 23 |
if selection_set: |
| 24 |
field_name = node.name.value |
| 25 |
self.report_error( |
| 26 |
GraphQLError( |
| 27 |
f"Field '{field_name}' must not have a selection" |
| 28 |
f" since type '{type_}' has no subfields.", |
| 29 |
selection_set, |
| 30 |
) |
| 31 |
) |
| 32 |
elif not selection_set: |
| 33 |
field_name = node.name.value |
| 34 |
self.report_error( |
| 35 |
GraphQLError( |
| 36 |
f"Field '{field_name}' of type '{type_}'" |
| 37 |
" must have a selection of subfields." |
| 38 |
f" Did you mean '{field_name} {{ ... }}'?", |
| 39 |
node, |
| 40 |
) |
| 41 |
) |
| 42 |
elif not selection_set.selections: |
| 43 |
field_name = node.name.value |
| 44 |
self.report_error( |
| 45 |
GraphQLError( |
| 46 |
f"Field '{field_name}' of type '{type_}'" |
| 47 |
" must have at least one field selected.", |
| 48 |
node, |
| 49 |
) |
| 50 |
) |