Skip to content

Commit

Permalink
Add BlobRef representation conversations
Browse files Browse the repository at this point in the history
  • Loading branch information
MarshalX committed Jun 20, 2024
1 parent 1d79690 commit d07e021
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
28 changes: 28 additions & 0 deletions packages/atproto_client/models/blob_ref.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,31 @@ def cid(self) -> 'CID':
return CID.decode(self.ref)

return CID.decode(self.ref.link)

def to_json_representation(self) -> 'BlobRef':
"""Get JSON representation.
Note:
Used in XRPC, etc. where JSON is used.
Returns:
BlobRef in JSON representation.
"""
if isinstance(self.ref, IpldLink):
return self

return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))

def to_bytes_representation(self) -> 'BlobRef':
"""Get bytes representation.
Note:
Used in Firehose, CAR, etc. where bytes are possible.
Returns:
BlobRef in bytes representation.
"""
if isinstance(self.ref, str):
return self

return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)
48 changes: 48 additions & 0 deletions tests/test_atproto_client/models/tests/test_blob_ref.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,51 @@ def test_blob_ref_to_ipld_json() -> None:
blob_ref2_raw = get_model_as_dict(blob_ref)
assert '$link' in blob_ref2_raw['ref']
assert plain_cid == blob_ref2_raw['ref']['$link']


def test_blob_ref_to_json_representation() -> None:
plain_cid = 'bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a'

bytes_blob_ref = BlobRef(
mime_type='text/plain',
size=0,
ref=plain_cid,
)

json_blob_ref = bytes_blob_ref.to_json_representation()
assert json_blob_ref.ref.link == bytes_blob_ref.ref
assert json_blob_ref.ref.link == plain_cid

json_blob_ref2 = BlobRef(
mime_type='text/plain',
size=0,
ref=IpldLink(link=plain_cid),
)
# JSON to JSON representation (nothing should happen)
json_blob_ref3 = json_blob_ref2.to_json_representation()
assert json_blob_ref3 is json_blob_ref2
assert json_blob_ref3 == json_blob_ref2


def test_blob_ref_to_bytes_representation() -> None:
plain_cid = 'bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a'

json_blob_ref = BlobRef(
mime_type='text/plain',
size=0,
ref=IpldLink(link=plain_cid),
)

bytes_blob_ref = json_blob_ref.to_bytes_representation()
assert bytes_blob_ref.ref == json_blob_ref.ref.link
assert bytes_blob_ref.ref == plain_cid

bytes_blob_ref2 = BlobRef(
mime_type='text/plain',
size=0,
ref=plain_cid,
)
# Bytes to Bytes representation (nothing should happen)
bytes_blob_ref3 = bytes_blob_ref2.to_bytes_representation()
assert bytes_blob_ref3 is bytes_blob_ref2
assert bytes_blob_ref3 == bytes_blob_ref2

0 comments on commit d07e021

Please sign in to comment.