|
| 1 | + |
| 2 | +# Copyright (c) 2022 Asif Arman Rahman |
| 3 | +# Licensed under MIT (https://github.com/AsifArmanRahman/firebase/blob/main/LICENSE) |
| 4 | + |
| 5 | +# -------------------------------------------------------------------------------------- |
| 6 | + |
| 7 | + |
| 8 | +from base64 import b64decode |
| 9 | + |
| 10 | + |
| 11 | +def _from_datastore(data): |
| 12 | + """ Converts a map of Firestore ``data``-s to Python dictionary. |
| 13 | +
|
| 14 | +
|
| 15 | + :type data: dict |
| 16 | + :param data: A map of firestore data. |
| 17 | +
|
| 18 | +
|
| 19 | + :return: A dictionary of native Python values converted |
| 20 | + from the ``data``. |
| 21 | + :rtype: dict |
| 22 | + """ |
| 23 | + |
| 24 | + data_to_restructure = data['fields'] |
| 25 | + |
| 26 | + for key, val in data_to_restructure.items(): |
| 27 | + |
| 28 | + if val.get('mapValue'): |
| 29 | + data_to_restructure[key] = _from_datastore(val['mapValue']) |
| 30 | + |
| 31 | + elif val.get('arrayValue'): |
| 32 | + arr = [] |
| 33 | + |
| 34 | + for x in val['arrayValue']['values']: |
| 35 | + arr.append(_decode_datastore(x)) |
| 36 | + |
| 37 | + data_to_restructure[key] = arr |
| 38 | + |
| 39 | + else: |
| 40 | + data_to_restructure[key] = _decode_datastore(val) |
| 41 | + |
| 42 | + return data_to_restructure |
| 43 | + |
| 44 | + |
| 45 | +def _decode_datastore(value): |
| 46 | + """ Converts a Firestore ``value`` to a native Python value. |
| 47 | +
|
| 48 | +
|
| 49 | + :type value: dict |
| 50 | + :param value: A Firestore data to be decoded / parsed / |
| 51 | + converted. |
| 52 | +
|
| 53 | +
|
| 54 | + :return: A native Python value converted from the ``value``. |
| 55 | + :rtype: :data:`None` or :class:`bool` or :class:`bytes` |
| 56 | + or :class:`int` or :class:`float` or :class:`str` or |
| 57 | + :class:`dict` |
| 58 | +
|
| 59 | + :raises TypeError: For value types that are unsupported. |
| 60 | + """ |
| 61 | + |
| 62 | + if value.get('nullValue', False) is None: |
| 63 | + return value['nullValue'] |
| 64 | + |
| 65 | + elif value.get('booleanValue') is not None: |
| 66 | + return bool(value['booleanValue']) |
| 67 | + |
| 68 | + elif value.get('bytesValue'): |
| 69 | + return b64decode(value['bytesValue'].encode('utf-8')) |
| 70 | + |
| 71 | + elif value.get('integerValue'): |
| 72 | + return int(value['integerValue']) |
| 73 | + |
| 74 | + elif value.get('doubleValue'): |
| 75 | + return float(value['doubleValue']) |
| 76 | + |
| 77 | + elif value.get('stringValue'): |
| 78 | + return str(value['stringValue']) |
| 79 | + |
| 80 | + elif value.get('mapValue'): |
| 81 | + return _from_datastore(value['mapValue']) |
| 82 | + |
| 83 | + else: |
| 84 | + raise TypeError("Cannot convert to a Python Value", value, "Invalid type", type(value)) |
0 commit comments