summaryrefslogtreecommitdiffstats
path: root/python/fatcat_tools/transforms/entities.py
blob: b67df12ded465a3265f39da0adfb7f1e8b54eb41 (plain)
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


import collections
from fatcat_client import ApiClient

def entity_to_dict(entity, api_client=None):
    """
    Hack to take advantage of the code-generated serialization code.

    Initializing/destroying ApiClient objects is surprisingly expensive
    (because it involves a threadpool), so we allow passing an existing
    instance. If you already have a full-on API connection `api`, you can
    access the ApiClient object as `api.api_client`. This is such a speed-up
    that this argument may become mandatory.
    """
    if not api_client:
        api_client = ApiClient()
    return api_client.sanitize_for_serialization(entity)

def entity_from_json(json_str, entity_type, api_client=None):
    """
    Hack to take advantage of the code-generated deserialization code

    See not on `entity_to_dict()` about api_client argument.
    """
    if not api_client:
        api_client = ApiClient()
    thing = collections.namedtuple('Thing', ['data'])
    thing.data = json_str
    return api_client.deserialize(thing, entity_type)