neon_arch commited on
Commit
4c298ce
1 Parent(s): 7b1f93b

⚙️ refactor: add code to initialize redis cache struct only once (#180)(#178)

Browse files
Files changed (1) hide show
  1. src/server/routes.rs +15 -3
src/server/routes.rs CHANGED
@@ -16,6 +16,10 @@ use handlebars::Handlebars;
16
  use serde::Deserialize;
17
  use tokio::join;
18
 
 
 
 
 
19
  /// A named struct which deserializes all the user provided search parameters and stores them.
20
  ///
21
  /// # Fields
@@ -158,10 +162,17 @@ async fn results(
158
  page: u32,
159
  req: &HttpRequest,
160
  ) -> Result<SearchResults, Box<dyn std::error::Error>> {
161
- //Initialize redis cache connection struct
162
- let mut redis_cache = RedisCache::new(&config.redis_url, 5).await?;
 
 
 
 
 
 
163
  // fetch the cached results json.
164
- let cached_results_json = redis_cache.cached_json(&url).await;
 
165
  // check if fetched cache results was indeed fetched or it was an error and if so
166
  // handle the data accordingly.
167
  match cached_results_json {
@@ -205,6 +216,7 @@ async fn results(
205
  };
206
  results.add_style(&config.style);
207
  redis_cache
 
208
  .cache_results(&serde_json::to_string(&results)?, &url)
209
  .await?;
210
  Ok(results)
 
16
  use serde::Deserialize;
17
  use tokio::join;
18
 
19
+ // ---- Constants ----
20
+ /// Initialize redis cache connection once and store it on the heap.
21
+ const REDIS_CACHE: async_once_cell::OnceCell<RedisCache> = async_once_cell::OnceCell::new();
22
+
23
  /// A named struct which deserializes all the user provided search parameters and stores them.
24
  ///
25
  /// # Fields
 
162
  page: u32,
163
  req: &HttpRequest,
164
  ) -> Result<SearchResults, Box<dyn std::error::Error>> {
165
+ let redis_cache: RedisCache = REDIS_CACHE
166
+ .get_or_init(async {
167
+ // Initialize redis cache connection pool only one and store it in the heap.
168
+ RedisCache::new(&config.redis_url, 5).await.unwrap()
169
+ })
170
+ .await
171
+ .clone();
172
+
173
  // fetch the cached results json.
174
+ let cached_results_json: Result<String, error_stack::Report<crate::cache::error::PoolError>> =
175
+ redis_cache.clone().cached_json(&url).await;
176
  // check if fetched cache results was indeed fetched or it was an error and if so
177
  // handle the data accordingly.
178
  match cached_results_json {
 
216
  };
217
  results.add_style(&config.style);
218
  redis_cache
219
+ .clone()
220
  .cache_results(&serde_json::to_string(&results)?, &url)
221
  .await?;
222
  Ok(results)