soph_cache/support/
cache.rs

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
use crate::{config, support::drivers, traits::CacheDriver, Cache, CacheResult};

impl Cache {
    pub fn new(driver: Box<dyn CacheDriver>, config: config::Cache) -> Self {
        Self { driver, config }
    }

    pub fn try_from_config(config: config::Cache) -> CacheResult<Self> {
        let driver = match config.driver {
            config::Driver::Null => drivers::null::new(),
            #[cfg(feature = "memory")]
            config::Driver::Memory => drivers::mem::new(),
        };

        Ok(Self::new(driver, config))
    }

    pub fn config(self) -> config::Cache {
        self.config
    }

    pub async fn has(&self, key: &str) -> CacheResult<bool> {
        self.driver.has(key).await
    }

    pub async fn get(&self, key: &str) -> CacheResult<Option<String>> {
        self.driver.get(key).await
    }

    pub async fn insert(&self, key: &str, value: &str) -> CacheResult<()> {
        self.driver.insert(key, value).await
    }

    pub async fn remove(&self, key: &str) -> CacheResult<()> {
        self.driver.remove(key).await
    }

    pub async fn clear(&self) -> CacheResult<()> {
        self.driver.clear().await
    }
}

impl std::ops::Deref for Cache {
    type Target = Box<dyn CacheDriver>;

    fn deref(&self) -> &Self::Target {
        &self.driver
    }
}