diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 285a0d238c..6c1901aec3 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -1,4 +1,5 @@ pub mod address; +pub mod cache; pub mod configs; pub mod connector_response; pub mod customers; diff --git a/crates/router/src/db/cache.rs b/crates/router/src/db/cache.rs new file mode 100644 index 0000000000..c543695d22 --- /dev/null +++ b/crates/router/src/db/cache.rs @@ -0,0 +1,57 @@ +#![allow(dead_code)] + +use error_stack::ResultExt; + +use super::Store; +use crate::core::errors::{self, CustomResult}; + +pub async fn get_or_populate_cache( + store: &Store, + key: &str, + fun: F, +) -> CustomResult +where + T: serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug, + F: FnOnce() -> Fut + Send, + Fut: futures::Future> + Send, +{ + let redis = &store.redis_conn; + let redis_val = redis + .get_and_deserialize_key::(key, std::any::type_name::()) + .await; + match redis_val { + Err(err) => match err.current_context() { + errors::RedisError::NotFound => { + let data = fun().await?; + redis + .serialize_and_set_key(key, &data) + .await + .change_context(errors::StorageError::KVError)?; + Ok(data) + } + _ => Err(err + .change_context(errors::StorageError::KVError) + .attach_printable("Error while fetching config")), + }, + Ok(val) => Ok(val), + } +} + +pub async fn redact_cache( + store: &Store, + key: &str, + fun: F, +) -> CustomResult +where + T: serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug, + F: FnOnce() -> Fut + Send, + Fut: futures::Future> + Send, +{ + let data = fun().await?; + store + .redis_conn + .delete_key(key) + .await + .change_context(errors::StorageError::KVError)?; + Ok(data) +}