1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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(())
}