Skip to main content

aet_file_settings/
lib.rs

1use std::io::prelude::*;
2use std::path::Path;
3use std::fs::File;
4use std::fs;
5use serde::Serialize;
6use serde::de::DeserializeOwned;
7
8static FILE_PATH: &str = "./Data";
9static FILE_NAME: &str = "appsettings.json";
10
11pub struct SettingsFile {}
12
13impl SettingsFile {
14    pub fn get<T: DeserializeOwned>() -> std::io::Result<T> {
15        verify_path_and_file_exists()?;
16
17        let file_path = Path::new(FILE_PATH).join(FILE_NAME);
18
19        let mut file = File::open(&file_path)?;
20
21        let mut contents = String::new();
22
23        file.read_to_string(&mut contents)?;
24
25        let json_obj: T = serde_json::from_str(contents.as_str())?;
26
27        Ok(json_obj)
28    }
29
30    pub fn save<T: Serialize>(data: T) -> std::io::Result<()> {
31        let json = serde_json::to_string(&data)?;
32
33        verify_path_and_file_exists()?;
34
35        let file_path = Path::new(FILE_PATH).join(FILE_NAME);
36
37        fs::write(file_path, json)?;
38
39        Ok(())
40    }
41}
42
43fn verify_path_and_file_exists() -> std::io::Result<()> {
44    let directory_path = Path::new(FILE_PATH);
45
46    if !directory_path.exists() {
47        fs::create_dir(FILE_PATH)?;
48    }
49
50    let file_path = directory_path.join(FILE_NAME);
51
52    if !file_path.exists() {
53        File::create(&file_path)?;
54
55        fs::write(file_path, "{}").expect("Unable to write file");
56    }
57
58    Ok(())
59}