use crate::resolution::parser::DidCheqdParser;
use crate::resolution::resolver::{DidCheqdResolver, DidCheqdResolverConfiguration};
use crate::resolution::transformer::cheqd_diddoc_to_json;
use serde_json::to_vec;
use ssi_dids_core::{
DIDMethod, DIDResolver,
document::{self, representation::MediaType},
resolution::{Error, Metadata as ResolutionMetadata, Options, Output},
};
pub mod error;
pub mod proto;
pub mod resolution;
pub struct DIDCheqd {
pub config: DidCheqdResolverConfiguration,
}
impl DIDCheqd {
pub fn new(config: Option<DidCheqdResolverConfiguration>) -> Self {
Self {
config: config.unwrap_or_default(),
}
}
}
impl Default for DIDCheqd {
fn default() -> Self {
Self::new(None)
}
}
impl DIDMethod for DIDCheqd {
const DID_METHOD_NAME: &'static str = "cheqd";
}
impl DIDResolver for DIDCheqd {
async fn resolve_representation<'a>(
&'a self,
did: &'a ssi_dids_core::DID,
options: Options,
) -> Result<Output<Vec<u8>>, Error> {
let cfg = self.config.clone();
let resolver = DidCheqdResolver::new(cfg);
let parsed = DidCheqdParser::parse(did.as_str())
.map_err(|e| Error::InvalidMethodSpecificId(e.to_string()))?;
if parsed.query.is_some() {
match resolver.query_resource_by_str(did.as_str(), parsed).await {
Ok((content_bytes, media_type)) => {
return Ok(Output::new(
content_bytes,
document::Metadata::default(),
ResolutionMetadata::from_content_type(media_type),
));
}
Err(e) => return Err(Error::internal(format!("cheqd resolver error: {e:?}"))),
}
}
match resolver.query_did_doc_by_str(did.as_str(), parsed).await {
Ok((proto_doc, metadata)) => {
let json_value = cheqd_diddoc_to_json(proto_doc)
.map_err(|e| Error::internal(format!("cheqd transform error: {e:?}")))?;
let json = to_vec(&json_value).map_err(|e| {
Error::internal(format!("failed to serialize DID document: {e}"))
})?;
let content_type = options.accept.unwrap_or(MediaType::JsonLd);
Ok(Output::new(
json,
match metadata {
Some(meta) => document::Metadata {
deactivated: Some(meta.deactivated),
},
None => document::Metadata { deactivated: None },
},
ResolutionMetadata::from_content_type(Some(content_type.to_string())),
))
}
Err(e) => Err(Error::internal(format!("cheqd resolver error: {e:?}"))),
}
}
}