From bd1530a4e282876b1015671f80fa34fcfb56fb77 Mon Sep 17 00:00:00 2001 From: Philippe Loctaux Date: Tue, 7 Mar 2023 22:52:06 +0100 Subject: [PATCH] ezidam: ability to cache routes as well as types --- crates/ezidam/src/cache.rs | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/crates/ezidam/src/cache.rs b/crates/ezidam/src/cache.rs index 1af6fba..8971cf5 100644 --- a/crates/ezidam/src/cache.rs +++ b/crates/ezidam/src/cache.rs @@ -4,16 +4,18 @@ use rocket::{Build, Request, Response, Rocket}; #[derive(Debug)] pub struct CacheControl { - max_age: u32, - cache_types: Vec, + duration_secs: u32, + types: Vec, + routes: Vec<&'static str>, } impl Default for CacheControl { fn default() -> Self { CacheControl { // 60 secs * 60 minutes - max_age: 60 * 60, - cache_types: vec![ContentType::CSS, ContentType::JavaScript], + duration_secs: 60 * 60, + types: vec![ContentType::CSS, ContentType::JavaScript], + routes: vec!["/logo"], } } } @@ -33,14 +35,27 @@ impl Fairing for CacheControl { } } - async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) { + async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) { + let mut should_cache = false; + + // Check if content type matches if let Some(content_type) = response.content_type() { - if self.cache_types.contains(&content_type) { - response.set_header(Header::new( - "Cache-Control", - format!("public, max-age={}", self.max_age), - )); + if self.types.contains(&content_type) { + should_cache = true; } } + + // Check if route matches + self.routes + .iter() + .filter(|s| request.uri().path().starts_with(*s)) + .for_each(|_| should_cache = true); + + if should_cache { + response.set_header(Header::new( + "Cache-Control", + format!("public, max-age={}", self.duration_secs), + )); + } } }