use std::sync::Arc;
use async_trait::async_trait;
use bytes::Bytes;
use cid::Cid;
use serde::{Deserialize, Serialize};
use helia_interface::Helia;
use multihash_codetable::{Code, MultihashDigest};
use crate::{AddOptions, GetOptions, JsonError};
pub const JSON_CODEC: u64 = 0x0200;
#[async_trait]
pub trait JsonInterface {
async fn add<T>(&self, object: &T, options: Option<AddOptions>) -> Result<Cid, JsonError>
where
T: Serialize + Send + Sync;
async fn get<T>(&self, cid: &Cid, options: Option<GetOptions>) -> Result<T, JsonError>
where
T: for<'de> Deserialize<'de>;
}
pub struct Json {
helia: Arc<dyn Helia>,
}
impl Json {
pub fn new(helia: Arc<dyn Helia>) -> Self {
Self { helia }
}
}
#[async_trait]
impl JsonInterface for Json {
async fn add<T>(&self, object: &T, options: Option<AddOptions>) -> Result<Cid, JsonError>
where
T: Serialize + Send + Sync,
{
let options = options.unwrap_or_default();
let json_data =
serde_json::to_vec(object).map_err(|e| JsonError::Serialization(e.to_string()))?;
let bytes = Bytes::from(json_data);
let mh = Code::Sha2_256.digest(&bytes);
let cid = Cid::new_v1(JSON_CODEC, mh);
self.helia
.blockstore()
.put(&cid, bytes, None)
.await
.map_err(|e| JsonError::Storage(e.to_string()))?;
if options.pin {
self.helia
.pins()
.add(&cid, None)
.await
.map_err(|e| JsonError::Storage(format!("Failed to pin: {}", e)))?;
}
Ok(cid)
}
async fn get<T>(&self, cid: &Cid, _options: Option<GetOptions>) -> Result<T, JsonError>
where
T: for<'de> Deserialize<'de>,
{
if cid.codec() != JSON_CODEC {
return Err(JsonError::InvalidCodec {
expected: JSON_CODEC,
actual: cid.codec(),
});
}
let block_bytes = self
.helia
.blockstore()
.get(cid, None)
.await
.map_err(|e| JsonError::Retrieval(e.to_string()))?;
let object: T = serde_json::from_slice(&block_bytes)
.map_err(|e| JsonError::Deserialization(e.to_string()))?;
Ok(object)
}
}