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
64
65
66
67
68
69
pub mod drivers;
pub mod traits;

use crate::traits::{CacheDriver, CacheResult};
use ayun_config::traits::ConfigurationTrait;
use ayun_core::{
    errors::ContainerError,
    traits::{ErrorTrait, InstanceTrait},
    Container,
};

pub type Error = ayun_core::Error;

pub type Result<T, E = Error> = ayun_core::Result<T, E>;

pub struct Cache {
    driver: Box<dyn CacheDriver>,
}

impl InstanceTrait for Cache {
    fn register(container: &Container) -> Result<Self, ContainerError>
    where
        Self: Sized,
    {
        let config = container
            .resolve::<ayun_config::Config>()?
            .get::<ayun_config::config::Cache>("cache")
            .map_err(Error::wrap)?;

        let driver = match config.driver {
            ayun_config::config::CacheDriver::Null => drivers::null::new(),
            #[cfg(feature = "cache-redis")]
            ayun_config::config::CacheDriver::Redis => {
                let redis = container.resolve::<ayun_redis::Redis>()?;
                drivers::redis::new(redis.clone())
            }
            #[cfg(feature = "cache-memory")]
            ayun_config::config::CacheDriver::Memory => drivers::mem::new(),
        };

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

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

    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
    }
}