Skip to content

Commit

Permalink
feat(db): add find_config_by_key_unwrap_or (#2214)
Browse files Browse the repository at this point in the history
  • Loading branch information
Abhicodes-crypto authored Sep 21, 2023
1 parent eb56b2c commit 2bd2526
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions crates/router/src/db/configs.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit 2bd2526

Please sign in to comment.