From 2bd25261b43b8b89ff2042e944ffa6008cc77c8f Mon Sep 17 00:00:00 2001 From: Abhishek Marrivagu <68317979+Abhicodes-crypto@users.noreply.github.com> Date: Thu, 21 Sep 2023 21:35:53 +0530 Subject: [PATCH] feat(db): add find_config_by_key_unwrap_or (#2214) --- crates/router/src/db/configs.rs | 55 +++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/crates/router/src/db/configs.rs b/crates/router/src/db/configs.rs index 411f785547..dacb9d7b37 100644 --- a/crates/router/src/db/configs.rs +++ b/crates/router/src/db/configs.rs @@ -1,3 +1,4 @@ +use common_utils::ext_traits::AsyncExt; use diesel_models::configs::ConfigUpdateInternal; use error_stack::{IntoReport, ResultExt}; use router_env::{instrument, tracing}; @@ -26,6 +27,13 @@ pub trait ConfigInterface { key: &str, ) -> CustomResult; + async fn find_config_by_key_unwrap_or( + &self, + key: &str, + // If the config is not found it will be created with the default value. + default_config: Option, + ) -> CustomResult; + async fn find_config_by_key_from_db( &self, key: &str, @@ -106,6 +114,45 @@ impl ConfigInterface for Store { .await } + async fn find_config_by_key_unwrap_or( + &self, + key: &str, + // If the config is not found it will be created with the default value. + default_config: Option, + ) -> CustomResult { + let find_else_unwrap_or = || async { + let conn = connection::pg_connection_write(self).await?; + match storage::Config::find_by_key(&conn, key) + .await + .map_err(Into::::into) + .into_report() + { + Ok(a) => Ok(a), + Err(err) => { + if err.current_context().is_db_not_found() { + default_config + .ok_or(err) + .async_and_then(|c| async { + storage::ConfigNew { + key: key.to_string(), + config: c, + } + .insert(&conn) + .await + .map_err(Into::into) + .into_report() + }) + .await + } else { + Err(err) + } + } + } + }; + + cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await + } + async fn delete_config_by_key(&self, key: &str) -> CustomResult { let conn = connection::pg_connection_write(self).await?; let deleted = storage::Config::delete_by_key(&conn, key) @@ -207,6 +254,14 @@ impl ConfigInterface for MockDb { }) } + async fn find_config_by_key_unwrap_or( + &self, + key: &str, + _default_config: Option, + ) -> CustomResult { + self.find_config_by_key(key).await + } + async fn find_config_by_key_from_db( &self, key: &str,