From b22a5e587660f95f9952dc906f31a351dbde6c34 Mon Sep 17 00:00:00 2001 From: aleidk Date: Mon, 17 Mar 2025 14:56:20 -0300 Subject: [PATCH] fix: gracefully handle no db password --- src/config.rs | 23 ++++++++++++++++------- src/main.rs | 2 +- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/config.rs b/src/config.rs index d2de8e9..7fde8e0 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,7 +2,7 @@ use std::fmt::Display; use std::net::SocketAddr; use std::path::PathBuf; -use crate::Result; +use crate::{Error, Result}; use figment::providers::{Env, Format, Serialized, Toml}; use serde::{Deserialize, Serialize}; @@ -19,7 +19,11 @@ pub struct DBConfig { impl Display for DBConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.generate_db_string(true)) + write!( + f, + "{}", + self.generate_db_string(true).map_err(|_| std::fmt::Error)? + ) } } @@ -36,13 +40,16 @@ impl Default for DBConfig { } impl DBConfig { - pub fn generate_db_string(&self, ofuscate: bool) -> String { + pub fn generate_db_string(&self, ofuscate: bool) -> Result { if let Some(value) = &self.string { - return value.clone(); + return Ok(value.clone()); } let db_password = if ofuscate { - let mut db_password = self.password.clone().unwrap(); + let mut db_password = self + .password + .clone() + .ok_or(Error::Runtime("No database password provided"))?; let password_length = db_password.len(); let visible_characters = 4; @@ -59,7 +66,9 @@ impl DBConfig { db_password } else { - self.password.clone().unwrap() + self.password + .clone() + .ok_or(Error::Runtime("No database password provided"))? }; let db_string = format!( @@ -67,7 +76,7 @@ impl DBConfig { self.user, db_password, self.host, self.name, ); - db_string.to_owned() + Ok(db_string.to_owned()) } } diff --git a/src/main.rs b/src/main.rs index 62d55ab..4990567 100644 --- a/src/main.rs +++ b/src/main.rs @@ -62,7 +62,7 @@ async fn main() -> Result<()> { let pool = PgPoolOptions::new() .max_connections(5) - .connect(&config.db.generate_db_string(false)) + .connect(&config.db.generate_db_string(false)?) .await?; let (tx_state, tx_layer) = Tx::setup(pool);