fancy caching works now
This commit is contained in:
@@ -30,6 +30,9 @@ use std::sync::RwLock;
|
||||
use serde_json;
|
||||
use sysinfo::{System, Pid, RefreshKind, CpuRefreshKind, ProcessRefreshKind};
|
||||
|
||||
const POSTS_CACHE_PATH: &str = "./cache/posts_cache.json";
|
||||
const POST_STATS_PATH: &str = "./cache/post_stats.json";
|
||||
|
||||
#[derive(Debug, Deserialize, Clone, serde::Serialize)]
|
||||
pub struct PostFrontmatter {
|
||||
pub title: String,
|
||||
@@ -38,7 +41,7 @@ pub struct PostFrontmatter {
|
||||
pub summary: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Post {
|
||||
pub slug: String,
|
||||
pub title: String,
|
||||
@@ -50,7 +53,7 @@ pub struct Post {
|
||||
pub author: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, Default)]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
|
||||
pub struct PostStats {
|
||||
pub slug: String,
|
||||
pub cache_hits: u64,
|
||||
@@ -306,6 +309,8 @@ pub fn get_all_posts() -> Result<Vec<Post>, Box<dyn std::error::Error>> {
|
||||
if path.extension().map(|e| e == "md").unwrap_or(false) {
|
||||
let file_stem = path.file_stem().unwrap().to_string_lossy();
|
||||
if let Ok(post) = get_post_by_slug(&file_stem) {
|
||||
// Insert each post into the individual post cache as well
|
||||
POST_CACHE.write().unwrap().insert(file_stem.to_string(), post.clone());
|
||||
posts.push(post);
|
||||
}
|
||||
}
|
||||
@@ -342,4 +347,28 @@ pub fn watch_posts<F: Fn() + Send + 'static>(on_change: F) -> notify::Result<Rec
|
||||
}
|
||||
});
|
||||
Ok(watcher)
|
||||
}
|
||||
|
||||
pub fn load_post_cache_from_disk() {
|
||||
if let Ok(data) = fs::read_to_string(POSTS_CACHE_PATH) {
|
||||
if let Ok(map) = serde_json::from_str::<HashMap<String, Post>>(&data) {
|
||||
*POST_CACHE.write().unwrap() = map;
|
||||
}
|
||||
}
|
||||
if let Ok(data) = fs::read_to_string(POST_STATS_PATH) {
|
||||
if let Ok(map) = serde_json::from_str::<HashMap<String, PostStats>>(&data) {
|
||||
*POST_STATS.write().unwrap() = map;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save_post_cache_to_disk() {
|
||||
if let Ok(map) = serde_json::to_string(&*POST_CACHE.read().unwrap()) {
|
||||
let _ = fs::create_dir_all("./cache");
|
||||
let _ = fs::write(POSTS_CACHE_PATH, map);
|
||||
}
|
||||
if let Ok(map) = serde_json::to_string(&*POST_STATS.read().unwrap()) {
|
||||
let _ = fs::create_dir_all("./cache");
|
||||
let _ = fs::write(POST_STATS_PATH, map);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user