1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use crate::keys::{Key, KeyCollection};
use crate::storage::{KeyStorer, StorageError};
use async_trait::async_trait;

#[derive(Clone)]
pub struct RedactKeyStorer {
    url: String,
}

/// Stores an instance of a redact-backed key storer.
/// The redact-store server is an example implementation of a redact storage backing.
impl RedactKeyStorer {
    pub fn new(url: &str) -> Self {
        Self {
            url: url.to_owned(),
        }
    }
}

#[async_trait]
impl KeyStorer for RedactKeyStorer {
    async fn get(&self, name: &str) -> Result<Key, StorageError> {
        match reqwest::get(&format!("{}/keys/{}", self.url, name)).await {
            Ok(r) => Ok(r
                .json::<Key>()
                .await
                .map_err(|source| StorageError::InternalError {
                    source: Box::new(source),
                })?),
            Err(source) => Err(StorageError::InternalError {
                source: Box::new(source),
            }),
        }
    }

    async fn list(&self) -> Result<KeyCollection, StorageError> {
        match reqwest::get(&format!("{}/keys", self.url)).await {
            Ok(r) => Ok(r.json::<KeyCollection>().await.map_err(|source| {
                StorageError::InternalError {
                    source: Box::new(source),
                }
            })?),
            Err(source) => Err(StorageError::InternalError {
                source: Box::new(source),
            }),
        }
    }

    async fn create(&self, value: Key) -> Result<bool, StorageError> {
        let client = reqwest::Client::new();
        match client
            .post(&format!("{}/keys", self.url))
            .json(&value)
            .send()
            .await
        {
            Ok(_) => Ok(true),
            Err(source) => Err(StorageError::InternalError {
                source: Box::new(source),
            }),
        }
    }
}