refactor configs into a crate
This commit is contained in:
76
apps/api/src/configs.rs
Normal file
76
apps/api/src/configs.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
pub mod database;
|
||||
pub mod logging;
|
||||
pub mod server;
|
||||
|
||||
mod key;
|
||||
|
||||
use config::Config;
|
||||
use tracing::{debug, error};
|
||||
|
||||
pub trait FromConfig: Sized {
|
||||
fn from_config(config: &Config) -> Result<Self, String>;
|
||||
fn validate(&self) -> Result<(), String>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProgramSettings {
|
||||
pub logging: logging::LoggingSettings,
|
||||
pub database: database::DatabaseSettings,
|
||||
pub server: server::ServerSettings,
|
||||
}
|
||||
|
||||
impl FromConfig for ProgramSettings {
|
||||
fn from_config(_config: &Config) -> Result<Self, String> {
|
||||
let config = ProgramSettings {
|
||||
logging: logging::LoggingSettings::from_config(_config)?,
|
||||
database: database::DatabaseSettings::from_config(_config)?,
|
||||
server: server::ServerSettings::from_config(_config)?,
|
||||
};
|
||||
config.validate()?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
fn validate(&self) -> Result<(), String> {
|
||||
self.logging.validate()?;
|
||||
self.database.validate()?;
|
||||
self.server.validate()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_program_settings() -> ProgramSettings {
|
||||
debug!("Loading program settings from configuration sources");
|
||||
let settings = Config::builder()
|
||||
// dev / generated config has the highest priority (Overwrite by user config files)
|
||||
.add_source(config::File::with_name("generated-config.yaml").required(false))
|
||||
// user config files
|
||||
.add_source(
|
||||
config::File::with_name("/etc/yet-another-nginx-proxy-manager/config").required(false),
|
||||
)
|
||||
.add_source(
|
||||
config::File::with_name("$HOME/.config/yet-another-nginx-proxy-manager/config")
|
||||
.required(false),
|
||||
)
|
||||
.add_source(config::File::with_name("config.yaml").required(false))
|
||||
// environment variables have the highest priority (Overwrite all config files)
|
||||
.add_source(
|
||||
config::Environment::with_prefix("YANPM")
|
||||
.separator("__")
|
||||
.prefix_separator("_"),
|
||||
)
|
||||
.build()
|
||||
.expect("Failed to build configuration");
|
||||
|
||||
debug!("Configuration sources loaded successfully");
|
||||
debug!("Parsing program settings from configuration");
|
||||
|
||||
ProgramSettings::from_config(&settings)
|
||||
.inspect_err(|err| {
|
||||
error!("Configuration error: {}", err);
|
||||
debug!("Current configurations: {:#?}", settings);
|
||||
})
|
||||
.inspect(|_| {
|
||||
debug!("Program settings parsed successfully");
|
||||
})
|
||||
.expect("Failed to load program settings from configuration")
|
||||
}
|
||||
Reference in New Issue
Block a user