Flat file database editor and browser with web interface
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
rocket-inv/src/store/mod.rs

52 lines
1.1 KiB

use std::fs::{File, OpenOptions};
use std::io::{Read, Write, Error};
use std::path::Path;
use rocket::request::FromForm;
#[derive(Serialize,Deserialize)]
pub struct Store {
pub parts : Vec<Part>
}
#[derive(Serialize,Deserialize,FromForm)]
pub struct Part {
name : String,
quantity : usize,
location : String,
}
fn load_file_or(file : impl AsRef<Path>, def : String) -> String {
let mut file = match File::open(file) {
Ok(file) => file,
Err(_) => return def
};
let mut buf = String::new();
if file.read_to_string(&mut buf).is_err() {
return def;
}
buf
}
impl Store {
pub fn new() -> Self {
let mut file = load_file_or("inventory.json", "[]".to_string());
Store {
parts: serde_json::from_str(&file).unwrap(),
}
}
pub fn add(&mut self, part : Part) {
self.parts.push(part);
self.persist()
}
pub fn persist(&self) {
let mut file = OpenOptions::new().write(true).create(true).truncate(true).open("inventory.json").unwrap();
file.write(serde_json::to_string(&self.parts).unwrap().as_bytes()).unwrap();
}
}