Skip to main content

doido_cache/
namespaced.rs

1use crate::store::CacheStore;
2use doido_core::Result;
3use serde_json::Value;
4
5pub struct NamespacedStore<S: CacheStore> {
6    inner: S,
7    prefix: String,
8}
9
10impl<S: CacheStore> NamespacedStore<S> {
11    pub fn new(inner: S, prefix: impl Into<String>) -> Self {
12        Self {
13            inner,
14            prefix: prefix.into(),
15        }
16    }
17
18    fn full_key(&self, key: &str) -> String {
19        format!("{}:{}", self.prefix, key)
20    }
21}
22
23#[async_trait::async_trait]
24impl<S: CacheStore + Send + Sync> CacheStore for NamespacedStore<S> {
25    async fn get(&self, key: &str) -> Result<Option<Value>> {
26        self.inner.get(&self.full_key(key)).await
27    }
28    async fn set(&self, key: &str, value: Value, ttl: Option<u64>) -> Result<()> {
29        self.inner.set(&self.full_key(key), value, ttl).await
30    }
31    async fn delete(&self, key: &str) -> Result<()> {
32        self.inner.delete(&self.full_key(key)).await
33    }
34    async fn exists(&self, key: &str) -> Result<bool> {
35        self.inner.exists(&self.full_key(key)).await
36    }
37    async fn increment(&self, key: &str, by: i64) -> Result<i64> {
38        self.inner.increment(&self.full_key(key), by).await
39    }
40    async fn decrement(&self, key: &str, by: i64) -> Result<i64> {
41        self.inner.decrement(&self.full_key(key), by).await
42    }
43    async fn clear(&self) -> Result<()> {
44        self.inner.clear().await
45    }
46}