| 53 | } |
| 54 | |
| 55 | pub async fn cache_middleware( |
| 56 | req: ServiceRequest, |
| 57 | next: Next<impl MessageBody>, |
| 58 | ) -> Result<ServiceResponse<impl MessageBody>, Error> { |
| 59 | // Adjust cache expiry here |
| 60 | const MAX_AGE: u64 = 86400; |
| 61 | let cache_max_age = format!("max-age={MAX_AGE}").parse::<HeaderValue>().unwrap(); |
| 62 | // Defining cache key based on request path and query string |
| 63 | let key = if req.query_string().is_empty() { |
| 64 | req.path().to_owned() |
| 65 | } else { |
| 66 | format!("{}?{}", req.path(), req.query_string()) |
| 67 | }; |
| 68 | println!("cache key: {key:?}"); |
| 69 | |
| 70 | // Get "Cache-Control" request header and get cache directive |
| 71 | let headers = req.headers().to_owned(); |
| 72 | let cache_directive = match headers.get(CACHE_CONTROL) { |
| 73 | Some(cache_control_header) => cache_control_header.to_str().unwrap_or(""), |
| 74 | None => "", |
| 75 | }; |
| 76 | |
| 77 | // If cache directive is not "no-cache" and not "no-store" |
| 78 | if cache_directive != CacheDirective::NoCache.to_string() |
| 79 | && cache_directive != CacheDirective::NoStore.to_string() |
| 80 | && key != "/metrics" |
| 81 | { |
| 82 | // Initialize Redis Client from App Data |
| 83 | let redis_client = req.app_data::<RedisClient>(); |
| 84 | // This should always be Some, so let's unwrap |
| 85 | let mut redis_conn = redis_client.unwrap().get_connection(); |
| 86 | let redis_ok = redis_conn.is_ok(); |
| 87 | |
| 88 | // If Redis connection succeeded and request method is GET |
| 89 | if redis_ok && req.method() == Method::GET { |
| 90 | // Unwrap the connection |
| 91 | let redis_conn = redis_conn.as_mut().unwrap(); |
| 92 | |
| 93 | // Try to get the cached response by defined key |
| 94 | let cached_response: Result<Vec<u8>, RedisError> = redis_conn.get(key.to_owned()); |
| 95 | if let Err(e) = cached_response { |
| 96 | // If cache cannot be deserialized |
| 97 | println!("cache get error: {}", e); |
| 98 | } else if cached_response.as_ref().unwrap().is_empty() { |
| 99 | // If cache body is empty |
| 100 | println!("cache not found"); |
| 101 | } else { |
| 102 | // If cache is found |
| 103 | println!("cache found"); |
| 104 | |
| 105 | // Prepare response body |
| 106 | let res = HttpResponse::new(StatusCode::OK).set_body(cached_response.unwrap()); |
| 107 | let mut res = ServiceResponse::new(req.request().to_owned(), res); |
| 108 | |
| 109 | // Define content-type and headers here |
| 110 | res.headers_mut() |
| 111 | .append(CONTENT_TYPE, HeaderValue::from_static("application/json")); |
| 112 | res.headers_mut().append(CACHE_CONTROL, cache_max_age); |