Skip to main content

shared/infrastructure/cache/memcache/
adapter.rs

1use async_trait::async_trait;
2
3use crate::domain::cache::CacheAdapter;
4use crate::error::CoreError;
5
6#[derive(Clone)]
7pub struct MemCacheAdapter {
8    client: memcache::Client,
9}
10
11impl MemCacheAdapter {
12    pub fn new(client: memcache::Client) -> Self {
13        Self { client }
14    }
15}
16
17#[async_trait]
18impl CacheAdapter for MemCacheAdapter {
19    async fn insert(&self, key: &str, value: &str, expiration: u64) -> Result<(), CoreError> {
20        self.client
21            .add(key, value, expiration as u32)
22            .map_err(|e| e.into())
23    }
24
25    async fn find_one(&self, key: &str) -> Result<Option<String>, CoreError> {
26        self.client.get::<String>(key).map_err(|e| e.into())
27    }
28
29    async fn update(&self, key: &str, value: &str, expiration: u64) -> Result<(), CoreError> {
30        self.client
31            .replace(key, value, expiration as u32)
32            .map_err(|e| e.into())
33    }
34
35    async fn increment(&self, key: &str) -> Result<u64, CoreError> {
36        self.client.increment(key, 1).map_err(|e| e.into())
37    }
38
39    async fn delete_one(&self, key: &str) -> Result<(), CoreError> {
40        self.client.delete(key).map(|_| ()).map_err(|e| e.into())
41    }
42
43    async fn flush_all(&self) -> Result<(), CoreError> {
44        self.client.flush().map(|_| ()).map_err(|e| e.into())
45    }
46}