forked from realaravinth/libmedium
versioned migrations for cache
This commit is contained in:
parent
14c7225f82
commit
745d97acfd
1 changed files with 25 additions and 2 deletions
27
src/data.rs
27
src/data.rs
|
@ -19,10 +19,13 @@ use std::path::Path;
|
||||||
use actix_web::web;
|
use actix_web::web;
|
||||||
use graphql_client::{reqwest::post_graphql, GraphQLQuery};
|
use graphql_client::{reqwest::post_graphql, GraphQLQuery};
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
use sled::{Db, Tree};
|
use sled::{Db, Tree};
|
||||||
|
|
||||||
use crate::SETTINGS;
|
use crate::SETTINGS;
|
||||||
|
|
||||||
|
const CACHE_VERSION: usize = 1;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Data {
|
pub struct Data {
|
||||||
pub client: Client,
|
pub client: Client,
|
||||||
|
@ -47,11 +50,31 @@ impl Data {
|
||||||
let path = Path::new(SETTINGS.cache.as_ref().unwrap()).join("posts_cache");
|
let path = Path::new(SETTINGS.cache.as_ref().unwrap()).join("posts_cache");
|
||||||
let cache = sled::open(path).unwrap();
|
let cache = sled::open(path).unwrap();
|
||||||
let posts = cache.open_tree("posts").unwrap();
|
let posts = cache.open_tree("posts").unwrap();
|
||||||
AppData::new(Self {
|
let res = Self {
|
||||||
client: Client::new(),
|
client: Client::new(),
|
||||||
cache,
|
cache,
|
||||||
posts,
|
posts,
|
||||||
})
|
};
|
||||||
|
res.migrate();
|
||||||
|
|
||||||
|
AppData::new(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn migrate(&self) {
|
||||||
|
const KEY: &str = "POST_CACHE_VERSION";
|
||||||
|
let mut clean = true;
|
||||||
|
if let Ok(Some(v)) = self.posts.get(KEY) {
|
||||||
|
let version = bincode::deserialize::<usize>(&v[..]).unwrap();
|
||||||
|
clean = !(version == CACHE_VERSION);
|
||||||
|
}
|
||||||
|
|
||||||
|
if clean {
|
||||||
|
self.posts.clear().unwrap();
|
||||||
|
self.posts.flush().unwrap();
|
||||||
|
self.posts
|
||||||
|
.insert(KEY, bincode::serialize(&CACHE_VERSION).unwrap())
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_post(&self, id: &str) -> PostResp {
|
pub async fn get_post(&self, id: &str) -> PostResp {
|
||||||
|
|
Loading…
Reference in a new issue