idem_handler_config/
config.rs1use std::fs::File;
2use serde::de::DeserializeOwned;
3use std::path::MAIN_SEPARATOR_STR;
4
5#[derive(Default)]
6pub struct Config<C> {
7 config: C,
8}
9
10impl<C> Config<C>
11where
12 C: Default + DeserializeOwned
13{
14 pub fn new(provider: impl ConfigProvider<C>) -> Result<Self, ()> {
15 match provider.load() {
16 Ok(config) => Ok(Self{config}),
17 Err(_) => Err(())
18 }
19 }
20
21 pub fn get(&self) -> &C {
22 &self.config
23 }
24
25 pub fn get_mut(&mut self) -> &mut C {
26 &mut self.config
27 }
28}
29
30pub trait ConfigProvider<C>
31where
32 C: Default + DeserializeOwned
33{
34 fn load(&self) -> Result<C, ()>;
35}
36
37pub struct DefaultConfigProvider;
38
39impl<C> ConfigProvider<C> for DefaultConfigProvider
40where
41 C: Default + DeserializeOwned
42{
43 fn load(&self) -> Result<C, ()> {
44 Ok(C::default())
45 }
46}
47
48pub struct FileConfigProvider {
49 pub base_path: String,
50 pub config_name: String
51}
52
53impl<C> ConfigProvider<C> for FileConfigProvider
54where
55 C: Default + DeserializeOwned
56{
57 fn load(&self) -> Result<C, ()> {
58 let file = match File::open(format!("{}{}{}", self.base_path, MAIN_SEPARATOR_STR, self.config_name)) {
59 Ok(file) => file,
60 Err(_) => return Err(()),
61 };
62 match serde_json::from_reader(file) {
63 Ok(config) => Ok(config),
64 Err(_) => Err(())
65 }
66 }
67}
68
69pub enum ProviderType {
70 File,
71 Default
72}