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 } #[derive(Serialize,Deserialize,FromForm)] pub struct Part { name : String, quantity : usize, location : String, } fn load_file_or(file : impl AsRef, 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(); } }