| 1 |
from typing import Any, Dict, cast |
| 2 |
|
| 3 |
from ...error import GraphQLError |
| 4 |
from ...execution.collect_fields import collect_fields |
| 5 |
from ...language import ( |
| 6 |
FieldNode, |
| 7 |
FragmentDefinitionNode, |
| 8 |
OperationDefinitionNode, |
| 9 |
OperationType, |
| 10 |
) |
| 11 |
from . import ValidationRule |
| 12 |
|
| 13 |
__all__ = ["SingleFieldSubscriptionsRule"] |
| 14 |
|
| 15 |
|
| 16 |
class SingleFieldSubscriptionsRule(ValidationRule): |
| 17 |
"""Subscriptions must only include a single non-introspection field. |
| 18 |
|
| 19 |
A GraphQL subscription is valid only if it contains a single root field and |
| 20 |
that root field is not an introspection field. |
| 21 |
|
| 22 |
See https://spec.graphql.org/draft/#sec-Single-root-field |
| 23 |
""" |
| 24 |
|
| 25 |
def enter_operation_definition( |
| 26 |
self, node: OperationDefinitionNode, *_args: Any |
| 27 |
) -> None: |
| 28 |
if node.operation != OperationType.SUBSCRIPTION: |
| 29 |
return |
| 30 |
schema = self.context.schema |
| 31 |
subscription_type = schema.subscription_type |
| 32 |
if subscription_type: |
| 33 |
operation_name = node.name.value if node.name else None |
| 34 |
variable_values: Dict[str, Any] = {} |
| 35 |
document = self.context.document |
| 36 |
fragments: Dict[str, FragmentDefinitionNode] = { |
| 37 |
definition.name.value: definition |
| 38 |
for definition in document.definitions |
| 39 |
if isinstance(definition, FragmentDefinitionNode) |
| 40 |
} |
| 41 |
fields = collect_fields( |
| 42 |
schema, |
| 43 |
fragments, |
| 44 |
variable_values, |
| 45 |
subscription_type, |
| 46 |
node.selection_set, |
| 47 |
) |
| 48 |
if len(fields) > 1: |
| 49 |
field_selection_lists = list(fields.values()) |
| 50 |
extra_field_selection_lists = field_selection_lists[1:] |
| 51 |
extra_field_selection = [ |
| 52 |
field |
| 53 |
for fields in extra_field_selection_lists |
| 54 |
for field in ( |
| 55 |
fields |
| 56 |
if isinstance(fields, list) |
| 57 |
else [cast(FieldNode, fields)] |
| 58 |
) |
| 59 |
] |
| 60 |
self.report_error( |
| 61 |
GraphQLError( |
| 62 |
( |
| 63 |
"Anonymous Subscription" |
| 64 |
if operation_name is None |
| 65 |
else f"Subscription '{operation_name}'" |
| 66 |
) |
| 67 |
+ " must select only one top level field.", |
| 68 |
extra_field_selection, |
| 69 |
) |
| 70 |
) |
| 71 |
for field_nodes in fields.values(): |
| 72 |
field = field_nodes[0] |
| 73 |
field_name = field.name.value |
| 74 |
if field_name.startswith("__"): |
| 75 |
self.report_error( |
| 76 |
GraphQLError( |
| 77 |
( |
| 78 |
"Anonymous Subscription" |
| 79 |
if operation_name is None |
| 80 |
else f"Subscription '{operation_name}'" |
| 81 |
) |
| 82 |
+ " must not select an introspection top level field.", |
| 83 |
field_nodes, |
| 84 |
) |
| 85 |
) |