Debian Codegraph @

src/graphql/validation/rules/possible_fragment_spreads.py

raw
1 from typing import cast, Any, Optional
2
3 from ...error import GraphQLError
4 from ...language import FragmentSpreadNode, InlineFragmentNode
5 from ...type import GraphQLCompositeType, is_composite_type
6 from ...utilities import do_types_overlap, type_from_ast
7 from . import ValidationRule
8
9 __all__ = ["PossibleFragmentSpreadsRule"]
10
11
12 class PossibleFragmentSpreadsRule(ValidationRule):
13 """Possible fragment spread
14
15 A fragment spread is only valid if the type condition could ever possibly be true:
16 if there is a non-empty intersection of the possible parent types, and possible
17 types which pass the type condition.
18 """
19
20 def enter_inline_fragment(self, node: InlineFragmentNode, *_args: Any) -> None:
21 context = self.context
22 frag_type = context.get_type()
23 parent_type = context.get_parent_type()
24 if (
25 is_composite_type(frag_type)
26 and is_composite_type(parent_type)
27 and not do_types_overlap(
28 context.schema,
29 cast(GraphQLCompositeType, frag_type),
30 cast(GraphQLCompositeType, parent_type),
31 )
32 ):
33 context.report_error(
34 GraphQLError(
35 f"Fragment cannot be spread here as objects"
36 f" of type '{parent_type}' can never be of type '{frag_type}'.",
37 node,
38 )
39 )
40
41 def enter_fragment_spread(self, node: FragmentSpreadNode, *_args: Any) -> None:
42 context = self.context
43 frag_name = node.name.value
44 frag_type = self.get_fragment_type(frag_name)
45 parent_type = context.get_parent_type()
46 if (
47 frag_type
48 and parent_type
49 and not do_types_overlap(context.schema, frag_type, parent_type)
50 ):
51 context.report_error(
52 GraphQLError(
53 f"Fragment '{frag_name}' cannot be spread here as objects"
54 f" of type '{parent_type}' can never be of type '{frag_type}'.",
55 node,
56 )
57 )
58
59 def get_fragment_type(self, name: str) -> Optional[GraphQLCompositeType]:
60 context = self.context
61 frag = context.get_fragment(name)
62 if frag:
63 type_ = type_from_ast(context.schema, frag.type_condition)
64 if is_composite_type(type_):
65 return cast(GraphQLCompositeType, type_)
66 return None