gabrielsimmer.com/src/cache/mod.rs

59 lines
1.4 KiB
Rust
Raw Normal View History

use sqlx::FromRow;
use std::collections::HashMap;
2023-10-23 20:11:46 +01:00
use std::sync::{Mutex, OnceLock};
#[derive(Clone, Debug, FromRow)]
pub struct CachedItem {
pub content_type: String,
pub content: String,
pub cached: i64,
}
/// Determine whether we should actually use the cached item or not.
fn should_use(_item: &CachedItem) -> bool {
2023-10-07 18:01:15 +01:00
// let current_time: i64 = SystemTime::now()
// .duration_since(UNIX_EPOCH)
// .expect("SystemTime before UNIX EPOCH!")
// .as_secs()
// .try_into()
// .unwrap();
// current_time <= (item.cached + (2*60)) && item.content != ""
true
}
static CACHE: OnceLock<Mutex<HashMap<String, CachedItem>>> = OnceLock::new();
pub async fn get(key: &String) -> Option<CachedItem> {
2023-10-23 20:11:46 +01:00
let data = CACHE
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.unwrap();
dbg!(&key);
match data.get(key) {
Some(c) => {
if should_use(&c) {
Some(c.clone())
} else {
//let _rm = rm(key.to_string()).await;
None
}
}
None => None,
2023-10-02 15:33:19 +01:00
}
}
// async fn rm(key: String) {
// let mut data = CACHE.get().unwrap().clone();
// data.remove(&key);
// let _ = CACHE.set(data);
// }
pub async fn set(key: String, item: CachedItem) {
2023-10-23 20:11:46 +01:00
let mut data = CACHE
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.unwrap();
data.insert(key, item);
}