refactor: enhance env variable usage

This commit is contained in:
Sandro Eiler 2024-02-07 13:40:54 +01:00
parent e1c775066b
commit 0f427ba1d1
3 changed files with 21 additions and 0 deletions

12
Cargo.lock generated
View file

@ -1046,6 +1046,7 @@ dependencies = [
"reqwest",
"secrecy",
"serde",
"serde-aux",
"serde_json",
"sqlx",
"tokio",
@ -1849,6 +1850,17 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "serde-aux"
version = "4.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a86348501c129f3ad50c2f4635a01971f76974cd8a3f335988a0f1581c082765"
dependencies = [
"chrono",
"serde",
"serde_json",
]
[[package]]
name = "serde_derive"
version = "1.0.193"

View file

@ -18,6 +18,7 @@ hyper = { version = "1.1.0", features = ["full"] }
# Serde / json
serde = { version = "1.0", features = ["derive"] }
serde_json = "1"
serde-aux = "4"
# serde_with = "3"
# Axum
axum = { version = "0.7" }

View file

@ -1,4 +1,5 @@
use secrecy::{ExposeSecret, Secret};
use serde_aux::field_attributes::deserialize_number_from_string;
#[derive(serde::Deserialize)]
/// The setting collection.
@ -16,6 +17,7 @@ pub struct Settings {
/// * `port`: The port to listen on
/// * `host`: The host address to listen on
pub struct ApplicationSettings {
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
pub host: String,
}
@ -31,6 +33,7 @@ pub struct ApplicationSettings {
pub struct DatabaseSettings {
pub username: String,
pub password: Secret<String>,
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
pub host: String,
pub name: String,
@ -88,6 +91,11 @@ pub fn get_configuration() -> Result<Settings, config::ConfigError> {
.add_source(config::File::from(
configuration_directory.join(environment_filename),
))
.add_source(
config::Environment::with_prefix("APP")
.prefix_separator("_")
.separator("__"),
)
.build()?;
settings.try_deserialize::<Settings>()