use std::io::prelude::*;
use std::path::Path;
use std::fs::File;
use std::fs;
use serde::Serialize;
use serde::de::DeserializeOwned;
static FILE_PATH: &str = "./Data";
static FILE_NAME: &str = "appsettings.json";
pub struct SettingsFile {}
impl SettingsFile {
pub fn get<T: DeserializeOwned>() -> std::io::Result<T> {
verify_path_and_file_exists()?;
let file_path = Path::new(FILE_PATH).join(FILE_NAME);
let mut file = File::open(&file_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let json_obj: T = serde_json::from_str(contents.as_str())?;
Ok(json_obj)
}
pub fn save<T: Serialize>(data: T) -> std::io::Result<()> {
let json = serde_json::to_string(&data)?;
verify_path_and_file_exists()?;
let file_path = Path::new(FILE_PATH).join(FILE_NAME);
fs::write(file_path, json)?;
Ok(())
}
}
fn verify_path_and_file_exists() -> std::io::Result<()> {
let directory_path = Path::new(FILE_PATH);
if !directory_path.exists() {
fs::create_dir(FILE_PATH)?;
}
let file_path = directory_path.join(FILE_NAME);
if !file_path.exists() {
File::create(&file_path)?;
fs::write(file_path, "{}").expect("Unable to write file");
}
Ok(())
}