Skip to content
Clone
2308dd0
41 lines 1.2 KB Rust
use std::path::Path;
use figment::{
Figment,
providers::{Env, Format, Toml},
};
use crate::AppConfig;
use crate::error::ConfigError;
pub const ENV_PREFIX: &str = "APP_";
pub const ENV_SEPARATOR: &str = "__";
pub const DEFAULT_CONFIG_PATH: &str = "config/default.toml";
pub const LOCAL_CONFIG_PATH: &str = "config/local.toml";
pub fn figment() -> Figment {
let _ = dotenvy::dotenv();
let mut figment = Figment::new();
if Path::new(DEFAULT_CONFIG_PATH).exists() {
figment = figment.merge(Toml::file(DEFAULT_CONFIG_PATH));
}
if Path::new(LOCAL_CONFIG_PATH).exists() {
figment = figment.merge(Toml::file(LOCAL_CONFIG_PATH));
}
figment.merge(Env::prefixed(ENV_PREFIX).split(ENV_SEPARATOR))
}
pub fn load_default() -> Result<AppConfig, ConfigError> {
let cfg: AppConfig = figment().extract().map_err(ConfigError::from)?;
cfg.validate()?;
Ok(cfg)
}
pub fn load_from_env() -> Result<AppConfig, ConfigError> {
let _ = dotenvy::dotenv();
let figment = Figment::new().merge(Env::prefixed(ENV_PREFIX).split(ENV_SEPARATOR));
let cfg: AppConfig = figment.extract().map_err(ConfigError::from)?;
cfg.validate()?;
Ok(cfg)
}