2024-09-12 10:17:14 +02:00
|
|
|
use std::{
|
|
|
|
collections::HashMap,
|
|
|
|
ops::{Deref, DerefMut},
|
|
|
|
};
|
2024-09-02 18:40:02 +02:00
|
|
|
|
|
|
|
use serde::Deserialize;
|
|
|
|
|
2024-10-07 21:02:23 +02:00
|
|
|
#[derive(Debug, Clone)]
|
2024-09-02 18:40:02 +02:00
|
|
|
pub struct JSONStore<T> {
|
|
|
|
documents: HashMap<String, T>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: for<'a> Deserialize<'a>> JSONStore<T> {
|
|
|
|
pub fn new(dir: &str) -> Self {
|
|
|
|
let mut documents = HashMap::new();
|
|
|
|
|
|
|
|
for e in walkdir::WalkDir::new(dir)
|
|
|
|
.into_iter()
|
|
|
|
.filter_map(std::result::Result::ok)
|
|
|
|
{
|
|
|
|
if e.path().is_dir() {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if e.path().extension().is_none() {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.path().extension().unwrap().to_str().unwrap() == "json" {
|
|
|
|
let path = e.path().to_str().unwrap().to_owned();
|
|
|
|
let file_name = e.path().file_stem().unwrap().to_str().unwrap().to_string();
|
|
|
|
let content = std::fs::read_to_string(path).unwrap();
|
|
|
|
let json = serde_json::from_str(&content).unwrap();
|
|
|
|
|
|
|
|
documents.insert(file_name, json);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Self { documents }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Deref for JSONStore<T> {
|
|
|
|
type Target = HashMap<String, T>;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.documents
|
|
|
|
}
|
|
|
|
}
|
2024-09-12 10:17:14 +02:00
|
|
|
|
|
|
|
impl<T> DerefMut for JSONStore<T> {
|
|
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
|
|
&mut self.documents
|
|
|
|
}
|
|
|
|
}
|