br_addon/
tools.rs

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::fs;
use std::path::PathBuf;
#[cfg(feature = "kafka")]
use br_kafka::Kafka;
#[cfg(feature = "cache")]
use br_cache::{Cache, CacheConfig};
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
use br_db::Db;
use json::{object, JsonValue};
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
use br_db::config::Config;

/// 配置文件
#[derive(Clone)]
pub struct Tools {
    #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
    pub db: Db,
    #[cfg(feature = "cache")]
    pub cache: Cache,
    #[cfg(feature = "kafka")]
    pub kafka: Kafka,
}
impl Tools {
    pub fn new(path: PathBuf) -> Result<Self, String> {
        let res = match fs::read_to_string(path.clone()) {
            Ok(e) => e,
            Err(e) => {
                let res = Tools::config();
                let _ = fs::create_dir_all(path.parent().unwrap());
                fs::write(path, res.to_string()).map_err(|e| format!("{}", e))?;
                return Err(format!("{}", e));
            }
        };
        let res = json::parse(&res).or(Err("Failed to parse config"))?;

        Ok(Self {
            #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
            db: Db::new(res["db"].clone())?,
            #[cfg(feature = "cache")]
            cache: Cache::new(res["cache"].clone())?,
            #[cfg(feature = "kafka")]
            kafka: Kafka::new(res["kafka"].clone())?,
        })
    }
    fn config() -> JsonValue {
        let mut data = object! {};
        #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
        {
            data["db"] = Config::default().json();
        }
        #[cfg(feature = "cache")]{
            data["cache"] = CacheConfig::default().json();
        }
        #[cfg(feature = "kafka")]{
            data["kafka"] = Kafka::from(object! {}).json();
        }
        data
    }
}