-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathentity.py
146 lines (123 loc) · 5.49 KB
/
entity.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
from __future__ import annotations
from typing import Any
from typing import Dict, Type
from graphene import Enum, Field, List, NonNull, ObjectType, Scalar, Union
from graphene.types.schema import TypeMap
from graphene_directives import Schema
from graphene_directives.utils import has_non_field_attribute
from .apollo_versions import LATEST_VERSION, get_directive_from_name
from .scalars import _Any
def get_entities(schema: Schema) -> Dict[str, Any]:
"""
Find all the entities from the type map.
They can be easily distinguished from the other type as
the `@key` and `@extend` decorators adds a `_sdl` attribute to them.
"""
type_map: TypeMap = schema.graphql_schema.type_map
entities = {}
key_directive = get_directive_from_name("key", LATEST_VERSION)
extends_directive = get_directive_from_name("extends", LATEST_VERSION)
for type_name, type_ in type_map.items():
if not hasattr(type_, "graphene_type"):
continue
graphene_type = type_.graphene_type
is_entity = any(
[
has_non_field_attribute(graphene_type, key_directive),
has_non_field_attribute(graphene_type, extends_directive),
]
)
if is_entity:
entities[type_name] = graphene_type
return entities
def get_entity_cls(entities: Dict[str, Any]) -> Type[Union]:
"""
Create _Entity type which is a union of all the entity types.
"""
class _Entity(Union):
class Meta:
types = tuple(entities.values())
return _Entity
def get_entity_query(schema: Schema):
"""
Create Entity query.
"""
entities_dict = get_entities(schema)
if not entities_dict:
return
entity_type = get_entity_cls(entities_dict)
class EntityQuery:
entities = List(
entity_type,
name="_entities",
representations=NonNull(List(NonNull(_Any))),
required=True,
)
def resolve_entities(self, info, representations, sub_field_resolution=False):
entities = []
for representation in representations:
type_ = schema.graphql_schema.get_type(representation["__typename"])
model = type_.graphene_type
model_arguments = representation.copy()
model_arguments.pop("__typename")
if schema.auto_camelcase:
get_model_attr = schema.field_name_to_type_attribute(model)
model_arguments = {
get_model_attr(k): v for k, v in model_arguments.items()
}
# convert subfields of models from dict to a corresponding graphql type,
# This will be useful when @requires is used
for model_field, value in model_arguments.items():
if not hasattr(model, model_field):
continue
field = getattr(model, model_field)
if isinstance(field, Field) and isinstance(value, dict):
if value.get("__typename") is None:
value["__typename"] = field.type.of_type._meta.name # noqa
model_arguments[model_field] = EntityQuery.resolve_entities(
self,
info,
representations=[value],
sub_field_resolution=True,
).pop()
elif all(
[
isinstance(field, List),
isinstance(value, list),
any(
[
(
hasattr(field, "of_type")
and issubclass(field.of_type, ObjectType)
),
(
hasattr(field, "of_type")
and issubclass(field.of_type, Union)
),
]
),
]
):
for sub_value in value:
if sub_value.get("__typename") is None:
sub_value[
"__typename"
] = field.of_type._meta.name # noqa
model_arguments[model_field] = EntityQuery.resolve_entities(
self, info, representations=value, sub_field_resolution=True
)
elif isinstance(field, Scalar) and getattr(
field, "parse_value", None
):
model_arguments[model_field] = field.parse_value(value)
elif isinstance(field, Enum):
model_arguments[model_field] = field._meta.enum[value] # noqa
model_instance = model(**model_arguments)
resolver = getattr(
model, "_%s__resolve_reference" % model.__name__, None
) or getattr(model, "_resolve_reference", None)
if resolver and not sub_field_resolution:
model_instance = resolver(model_instance, info)
entities.append(model_instance)
return entities
return EntityQuery