2019-08-18 00:07:53 +03:00
|
|
|
from collections.abc import Mapping
|
2018-07-01 13:29:45 +03:00
|
|
|
|
|
|
|
|
|
|
|
def deflate(node, index=None, path=None):
|
|
|
|
if index is None:
|
|
|
|
index = {}
|
|
|
|
if path is None:
|
|
|
|
path = []
|
|
|
|
|
2018-07-06 22:09:23 +03:00
|
|
|
if node and "id" in node and "__typename" in node:
|
|
|
|
route = ",".join(path)
|
|
|
|
cache_key = ":".join([route, str(node["__typename"]), str(node["id"])])
|
2018-07-01 13:29:45 +03:00
|
|
|
|
2018-07-01 13:32:16 +03:00
|
|
|
if index.get(cache_key) is True:
|
2018-07-06 22:09:23 +03:00
|
|
|
return {"__typename": node["__typename"], "id": node["id"]}
|
2018-07-01 13:29:45 +03:00
|
|
|
else:
|
2018-07-01 13:32:16 +03:00
|
|
|
index[cache_key] = True
|
2018-07-01 13:29:45 +03:00
|
|
|
|
2019-08-18 00:07:53 +03:00
|
|
|
result = {}
|
2018-07-01 13:29:45 +03:00
|
|
|
|
2019-08-18 00:07:53 +03:00
|
|
|
for field_name in node:
|
2018-07-01 13:29:45 +03:00
|
|
|
value = node[field_name]
|
|
|
|
|
|
|
|
new_path = path + [field_name]
|
|
|
|
if isinstance(value, (list, tuple)):
|
2018-07-06 22:09:23 +03:00
|
|
|
result[field_name] = [deflate(child, index, new_path) for child in value]
|
2018-07-01 13:29:45 +03:00
|
|
|
elif isinstance(value, Mapping):
|
|
|
|
result[field_name] = deflate(value, index, new_path)
|
|
|
|
else:
|
|
|
|
result[field_name] = value
|
|
|
|
|
|
|
|
return result
|