use config::Config; #[derive(serde::Deserialize, Debug)] #[serde(default)] pub struct DatabaseSettings { pub username: String, pub password: String, pub host: String, pub port: u16, pub database: String, } impl DatabaseSettings { pub fn url(&self) -> String { if self.password.is_empty() { format!( "postgres://{}@{}:{}/{}", self.username, self.host, self.port, self.database ) } else { format!( "postgres://{}:{}@{}:{}/{}", self.username, self.password, self.host, self.port, self.database ) } } } #[derive(serde::Deserialize, Debug)] #[serde(default)] pub struct Settings { pub database: DatabaseSettings, pub port: u16, } impl Default for DatabaseSettings { fn default() -> Self { DatabaseSettings { username: "newsletter".to_string(), password: "".to_string(), host: "localhost".to_string(), port: 5432, database: "newsletter".to_string(), } } } impl Default for Settings { fn default() -> Self { Settings { port: 3001, database: DatabaseSettings::default(), } } } pub fn get_configuration() -> Result { Config::builder() .add_source(config::File::with_name("./ztp.config").required(false)) .build()? .try_deserialize() } #[cfg(test)] mod tests { use super::*; #[test] fn test_for_defaults() { let maybe_config = get_configuration(); assert!(!maybe_config.is_err()); let config = maybe_config.unwrap(); assert_eq!(config.port, 3001); } }