use crate::{Paths, TakoyakiError};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{
fs::{create_dir_all, read_to_string, File},
io::Write,
path::PathBuf,
};
pub struct Cache {
cache_path: PathBuf,
}
impl Cache {
pub fn new(name: &str) -> Self {
Self {
cache_path: Paths::get_cache_path(name),
}
}
pub fn is_corrupted(&self) -> Result<bool, TakoyakiError> {
if !self.cache_path.exists() {
return Ok(true);
}
let raw = read_to_string(&self.cache_path)?;
serde_json::from_str::<Value>(&raw)?;
Ok(false)
}
pub fn get<T>(&self) -> Result<T, TakoyakiError>
where
T: for<'de> Deserialize<'de>,
{
self.is_corrupted()?;
let raw = read_to_string(&self.cache_path)?;
let parsed = serde_json::from_str(&raw)?;
Ok(parsed)
}
pub fn write<T>(&self, data: &T) -> Result<(), TakoyakiError>
where
T: Serialize,
{
create_dir_all(self.cache_path.parent().unwrap())?;
let mut cache_file = File::create(&self.cache_path)?;
let parsed = serde_json::to_string(data).unwrap();
cache_file.write_all(parsed.as_bytes())?;
Ok(())
}
}