async_graphql_dataloader/
cache.rs

1// src/cache.rs
2use std::{
3    hash::Hash,
4    time::{Duration, Instant},
5};
6
7pub struct Cache<K, V> {
8    store: dashmap::DashMap<K, (V, Instant)>,
9    ttl: Option<Duration>,
10}
11
12impl<K, V> Cache<K, V>
13where
14    K: Eq + Hash + Clone,
15    V: Clone,
16{
17    pub fn new() -> Self {
18        Self {
19            store: dashmap::DashMap::new(),
20            ttl: None,
21        }
22    }
23
24    pub fn with_ttl(mut self, ttl: Duration) -> Self {
25        self.ttl = Some(ttl);
26        self
27    }
28
29    pub fn get(&self, key: &K) -> Option<V> {
30        let entry = self.store.get(key)?;
31
32        if let Some(ttl) = self.ttl {
33            if entry.1.elapsed() > ttl {
34                self.store.remove(key);
35                return None;
36            }
37        }
38
39        Some(entry.0.clone())
40    }
41
42    pub fn set(&self, key: K, value: V) {
43        self.store.insert(key, (value, Instant::now()));
44    }
45
46    pub fn clear(&self) {
47        self.store.clear();
48    }
49}