Skip to main content

custom_store/
custom_store.rs

1use std::cell::RefCell;
2
3use config_easy::{SettingRow, SettingsQuery, SettingsStore};
4
5struct AppSettings {
6    rows: RefCell<Vec<SettingRow>>,
7}
8
9impl AppSettings {
10    fn new() -> Self {
11        Self {
12            rows: RefCell::new(vec![
13                SettingRow {
14                    key: "log_level".to_string(),
15                    value: "info".to_string(),
16                },
17                SettingRow {
18                    key: "api_token".to_string(),
19                    value: "secret-token".to_string(),
20                },
21            ]),
22        }
23    }
24}
25
26impl SettingsStore for AppSettings {
27    fn load_settings(
28        &self,
29        _query: &SettingsQuery<'_>,
30    ) -> Result<Vec<SettingRow>, Box<dyn std::error::Error + Send + Sync>> {
31        Ok(self.rows.borrow().clone())
32    }
33
34    fn update_setting(
35        &self,
36        _query: &SettingsQuery<'_>,
37        key: &str,
38        value: &str,
39    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
40        if let Some(row) = self.rows.borrow_mut().iter_mut().find(|row| row.key == key) {
41            row.value = value.to_string();
42        }
43
44        Ok(())
45    }
46}
47
48fn main() {
49    let store = AppSettings::new();
50
51    let _ = config_easy::builder(store)
52        .secret_keys(["api_token"])
53        .validator(|key, value| {
54            if key == "log_level" && !["debug", "info", "warn", "error"].contains(&value) {
55                return Err(std::io::Error::new(
56                    std::io::ErrorKind::InvalidInput,
57                    "expected one of debug, info, warn, error",
58                )
59                .into());
60            }
61
62            Ok(())
63        })
64        .action("reset", "reset settings", || {
65            println!("Reset settings here.");
66            Ok(())
67        })
68        .run();
69}