Skip to main content

did_example/
lib.rs

1/*!
2 * This module is a simple example of a DID resolver that uses a cache to store DID documents.
3 *
4 * Should only be used for local testing and development
5 *
6 * Enable using the did_example feature flag
7 */
8
9use affinidi_did_common::Document;
10use ahash::AHashMap as HashMap;
11use thiserror::Error;
12
13#[derive(Error, Debug)]
14pub enum DidExampleError {
15    #[error("Error parsing DID document: {0}")]
16    DocumentParseError(String),
17}
18
19#[derive(Clone, Default)]
20pub struct DiDExampleCache {
21    cache: HashMap<String, Document>,
22}
23
24impl DiDExampleCache {
25    fn from_string(document: String) -> Result<(String, Document), DidExampleError> {
26        let doc: Document = serde_json::from_str(&document).map_err(|e| {
27            DidExampleError::DocumentParseError(format!("Couldn't parse Document String: {e}",))
28        })?;
29
30        Ok((doc.id.to_string(), doc))
31    }
32
33    /// Create a new instance of the cache
34    pub fn new() -> Self {
35        DiDExampleCache {
36            cache: HashMap::new(),
37        }
38    }
39
40    /// Insert a DID document into the cache
41    /// `document`: A string representation of a DID document
42    pub fn insert_from_string(&mut self, document: &str) -> Result<(), DidExampleError> {
43        let (id, doc) = DiDExampleCache::from_string(document.to_string())?;
44        self.cache.insert(id, doc);
45        Ok(())
46    }
47
48    pub fn get(&self, id: &str) -> Option<&Document> {
49        self.cache.get(id)
50    }
51}