use async_trait::async_trait; use sqlx::FromRow; use std::{ fmt, time::{SystemTime, UNIX_EPOCH}, }; use std::collections::HashMap; use tokio::sync::Mutex; #[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 { 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 != "" } lazy_static! { static ref CACHE: Mutex> = Mutex::new(HashMap::new()); } pub async fn get(key: &String) -> Option { let data = CACHE.lock().await; 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, } } async fn rm(key: String) { let mut data = CACHE.lock().await; data.remove(&key); } pub async fn set(key: String, item: CachedItem) { let mut data = CACHE.lock().await; data.insert(key, item); }