Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(db): add find_config_by_key_unwrap_or (#2214)

Abhishek Marrivagu2bd25261b43b
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<storage::Config, errors::StorageError>;
+ 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<String>,
+ ) -> CustomResult<storage::Config, errors::StorageError>;
+
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<String>,
+ ) -> CustomResult<storage::Config, errors::StorageError> {
+ 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::<errors::StorageError>::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<bool, errors::StorageError> {
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<String>,
+ ) -> CustomResult<storage::Config, errors::StorageError> {
+ self.find_config_by_key(key).await
+ }
+
async fn find_config_by_key_from_db(
&self,
key: &str,