use config::{Config, Environment};
use std::ops::Deref;
use std::sync::RwLock;
use lazy_static::lazy_static;
use serde::Deserialize;
use super::error::Result;
lazy_static! {
static ref CONFIG: RwLock<Config> = RwLock::new(Config::new());
}
#[derive(Debug, Deserialize)]
pub struct Database {
pub url: String,
}
#[derive(Debug, Deserialize)]
pub struct AppConfig {
pub debug: bool,
pub database: Database,
}
impl AppConfig {
pub fn init(default_config: Option<&str>) -> Result<()> {
let mut settings = Config::new();
if let Some(config_contents) = default_config {
settings.merge(config::File::from_str(&config_contents, config::FileFormat::Toml))?;
}
settings.merge(Environment::with_prefix("APP"))?;
{
let mut w = CONFIG.write()?;
*w = settings;
}
Ok(())
}
pub fn merge_config(config_file: Option<&str>) -> Result<()> {
if let Some(config_file_path) = config_file {
{
CONFIG
.write()?
.merge(config::File::with_name(config_file_path))?;
}
}
Ok(())
}
pub fn set(key: &str, value: &str) -> Result<()> {
{
CONFIG.write()?.set(key, value)?;
}
Ok(())
}
pub fn get<'de, T>(key: &'de str) -> Result<T>
where
T: serde::Deserialize<'de>,
{
Ok(CONFIG.read()?.get::<T>(key)?)
}
pub fn fetch() -> Result<AppConfig> {
let r = CONFIG.read()?;
let config_clone = r.deref().clone();
Ok(config_clone.try_into()?)
}
}