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 ssi::dids::document::Document;
10use std::collections::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::from_json(&document)
27            .map_err(|e| {
28                DidExampleError::DocumentParseError(format!(
29                    "Couldn't parse Document String: {}",
30                    e
31                ))
32            })?
33            .into_document();
34
35        Ok((doc.id.to_string(), doc))
36    }
37
38    /// Create a new instance of the cache
39    pub fn new() -> Self {
40        DiDExampleCache {
41            cache: HashMap::new(),
42        }
43    }
44
45    /// Insert a DID document into the cache
46    /// `document`: A string representation of a DID document
47    pub fn insert_from_string(&mut self, document: &str) -> Result<(), DidExampleError> {
48        let (id, doc) = DiDExampleCache::from_string(document.to_string())?;
49        self.cache.insert(id, doc);
50        Ok(())
51    }
52
53    pub fn get(&self, id: &str) -> Option<&Document> {
54        self.cache.get(id)
55    }
56}