def decode(cls, data: meta.Datum, *, trigger_metadata) -> typing.Optional[cdb.DocumentList]: if data is None or data.type is None: return None data_type = data.type if data_type == 'string': body = data.value elif data_type == 'bytes': body = data.value.decode('utf-8') elif data_type == 'json': body = data.value else: raise NotImplementedError( f'unsupported queue payload type: {data_type}') documents = json.loads(body) if not isinstance(documents, list): documents = [documents] return cdb.DocumentList( (None if doc is None else cdb.Document.from_dict(doc)) for doc in documents)
def encode(cls, obj: typing.Any, *, expected_type: typing.Optional[type]) -> meta.Datum: if isinstance(obj, cdb.Document): data = cdb.DocumentList([obj]) elif isinstance(obj, cdb.DocumentList): data = obj elif isinstance(obj, collections.abc.Iterable): data = cdb.DocumentList() for doc in obj: if not isinstance(doc, cdb.Document): raise NotImplementedError else: data.append(doc) else: raise NotImplementedError return meta.Datum(type='json', value=json.dumps([dict(d) for d in data]))
def to_proto(cls, obj: typing.Any, *, pytype: typing.Optional[type]) -> protos.TypedData: if isinstance(obj, cdb.Document): data = cdb.DocumentList([obj]) elif isinstance(obj, cdb.DocumentList): data = obj elif isinstance(obj, collections.abc.Iterable): data = cdb.DocumentList() for doc in obj: if not isinstance(doc, cdb.Document): raise NotImplementedError else: data.append(doc) else: raise NotImplementedError return protos.TypedData( json=json.dumps([dict(d) for d in data]) )
def from_proto(cls, data: protos.TypedData, *, pytype: typing.Optional[type], trigger_metadata) -> cdb.DocumentList: data_type = data.WhichOneof('data') if data_type == 'string': body = data.string elif data_type == 'bytes': body = data.bytes.decode('utf-8') elif data_type == 'json': body = data.json else: raise NotImplementedError( f'unsupported queue payload type: {data_type}') documents = json.loads(body) if not isinstance(documents, list): documents = [documents] return cdb.DocumentList( cdb.Document.from_dict(doc) for doc in documents)