Skip to main content

xdid_method_web/
lib.rs

1//! [xdid](https://github.com/unavi-xyz/xdid) implementation of [did:web](https://w3c-ccg.github.io/did-method-web/).
2
3use reqwest::{Client, ClientBuilder};
4use xdid_core::{Method, MethodFuture, ResolutionError, did::Did, document::Document};
5
6pub use reqwest;
7
8mod parse;
9
10const NAME: &str = "web";
11
12pub struct MethodDidWeb {
13    pub client: Client,
14}
15
16impl MethodDidWeb {
17    /// Create a new did:web resolver.
18    ///
19    /// # Errors
20    ///
21    /// Returns an error if the HTTP client cannot be constructed.
22    pub fn new() -> Result<Self, reqwest::Error> {
23        let client = ClientBuilder::new().build()?;
24        Ok(Self { client })
25    }
26}
27
28impl Method for MethodDidWeb {
29    fn method_name(&self) -> &'static str {
30        NAME
31    }
32
33    #[cfg(not(target_family = "wasm"))]
34    fn resolve(&self, did: Did) -> MethodFuture<Result<Document, ResolutionError>> {
35        Box::pin(resolve_inner(self.client.clone(), did))
36    }
37
38    #[cfg(target_family = "wasm")]
39    fn resolve(&self, did: Did) -> MethodFuture<Result<Document, ResolutionError>> {
40        Box::pin(send_wrapper::SendWrapper::new(resolve_inner(
41            self.client.clone(),
42            did,
43        )))
44    }
45}
46
47async fn resolve_inner(client: Client, did: Did) -> Result<Document, ResolutionError> {
48    debug_assert_eq!(did.method_name.0, NAME);
49
50    let url = parse::parse_url(&did);
51
52    let req = client
53        .get(url)
54        .build()
55        .map_err(|_| ResolutionError::InvalidDid)?;
56
57    let doc = client
58        .execute(req)
59        .await
60        .map_err(|e| ResolutionError::ResolutionFailed(e.to_string()))?
61        .json::<Document>()
62        .await
63        .map_err(|e| ResolutionError::ResolutionFailed(e.to_string()))?;
64
65    Ok(doc)
66}