|
| 1 | +import collections.abc |
| 2 | +import json |
| 3 | +import typing |
| 4 | + |
| 5 | +from azure.functions import _cosmosdb as cdb |
| 6 | + |
| 7 | +from . import meta |
| 8 | +from .. import protos |
| 9 | + |
| 10 | + |
| 11 | +class CosmosDBConverter(meta.InConverter, meta.OutConverter, |
| 12 | + binding='cosmosDB'): |
| 13 | + |
| 14 | + @classmethod |
| 15 | + def check_input_type_annotation(cls, pytype: type) -> bool: |
| 16 | + return issubclass(pytype, cdb.DocumentList) |
| 17 | + |
| 18 | + @classmethod |
| 19 | + def check_output_type_annotation(cls, pytype: type) -> bool: |
| 20 | + return issubclass(pytype, (cdb.DocumentList, cdb.Document)) |
| 21 | + |
| 22 | + @classmethod |
| 23 | + def from_proto(cls, data: protos.TypedData, *, |
| 24 | + pytype: typing.Optional[type], |
| 25 | + trigger_metadata) -> cdb.DocumentList: |
| 26 | + data_type = data.WhichOneof('data') |
| 27 | + |
| 28 | + if data_type == 'string': |
| 29 | + body = data.string |
| 30 | + |
| 31 | + elif data_type == 'bytes': |
| 32 | + body = data.bytes.decode('utf-8') |
| 33 | + |
| 34 | + elif data_type == 'json': |
| 35 | + body = data.json |
| 36 | + |
| 37 | + else: |
| 38 | + raise NotImplementedError( |
| 39 | + f'unsupported queue payload type: {data_type}') |
| 40 | + |
| 41 | + documents = json.loads(body) |
| 42 | + if not isinstance(documents, list): |
| 43 | + documents = [documents] |
| 44 | + |
| 45 | + return cdb.DocumentList( |
| 46 | + cdb.Document.from_dict(doc) for doc in documents) |
| 47 | + |
| 48 | + @classmethod |
| 49 | + def to_proto(cls, obj: typing.Any, *, |
| 50 | + pytype: typing.Optional[type]) -> protos.TypedData: |
| 51 | + if isinstance(obj, cdb.Document): |
| 52 | + data = cdb.DocumentList([obj]) |
| 53 | + |
| 54 | + elif isinstance(obj, cdb.DocumentList): |
| 55 | + data = obj |
| 56 | + |
| 57 | + elif isinstance(obj, collections.abc.Iterable): |
| 58 | + data = cdb.DocumentList() |
| 59 | + |
| 60 | + for doc in obj: |
| 61 | + if not isinstance(doc, cdb.Document): |
| 62 | + raise NotImplementedError |
| 63 | + else: |
| 64 | + data.append(doc) |
| 65 | + |
| 66 | + else: |
| 67 | + raise NotImplementedError |
| 68 | + |
| 69 | + return protos.TypedData( |
| 70 | + json=json.dumps([dict(d) for d in data]) |
| 71 | + ) |
| 72 | + |
| 73 | + |
| 74 | +class CosmosDBTriggerConverter(CosmosDBConverter, |
| 75 | + binding='cosmosDBTrigger', trigger=True): |
| 76 | + pass |
0 commit comments