Automatically create admin on first start

This commit is contained in:
2022-03-29 19:32:31 +02:00
parent 2d062320a7
commit b4e8113706
13 changed files with 1773 additions and 2 deletions

View File

@@ -0,0 +1,43 @@
use std::path::{Path, PathBuf};
use crate::utils::err::Res;
pub struct EntityManager<E> {
file_path: PathBuf,
list: Vec<E>,
}
impl<E> EntityManager<E> where E: rocket::serde::Serialize + rocket::serde::DeserializeOwned + Eq + Clone {
/// Open entity
pub fn open_or_create<A: AsRef<Path>>(path: A) -> Res<Self> {
if !path.as_ref().is_file() {
log::warn!("Entities at {:?} does not point to a file, creating a new empty entity container...", path.as_ref());
return Ok(Self {
file_path: path.as_ref().to_path_buf(),
list: vec![],
});
}
log::info!("Open existing entity file {:?}", path.as_ref());
Ok(Self {
file_path: path.as_ref().to_path_buf(),
list: serde_json::from_str(&std::fs::read_to_string(path.as_ref())?)?,
})
}
/// Get the number of entries in the list
pub fn len(&self) -> usize {
self.list.len()
}
/// Save the list
fn save(&self) -> Res {
Ok(std::fs::write(&self.file_path, serde_json::to_string(&self.list)?)?)
}
/// Insert a new element in the list
pub fn insert(&mut self, el: E) -> Res {
self.list.push(el);
self.save()
}
}