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