Skip to content

Commit f5ec8c5

Browse files
committed
Only cache suffessful responses & respond with proper status codes
1 parent e8dc416 commit f5ec8c5

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/api/common/caching.rs

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
use actix_web::{
22
HttpResponse,
3+
HttpResponseBuilder,
34
body::{BoxBody, EitherBody, MessageBody},
45
dev::{ServiceRequest, ServiceResponse},
5-
http::header::{ETAG, HeaderMap, HeaderValue, IF_NONE_MATCH},
6+
http::{
7+
StatusCode,
8+
header::{ETAG, HeaderMap, HeaderValue, IF_NONE_MATCH}
9+
},
610
middleware::Next,
711
web::{self, Bytes}
812
};
@@ -28,6 +32,7 @@ pub type ETagType = [u8; 32];
2832
pub struct CacheValue {
2933
pub response: Bytes,
3034
pub headers: HeaderMap,
35+
pub status: StatusCode,
3136
pub etag: ETagType
3237
}
3338

@@ -103,7 +108,7 @@ pub async fn middleware(
103108
return Ok(service_request.into_response(res).map_into_right_body());
104109
}
105110

106-
let mut res = HttpResponse::Ok()
111+
let mut res = HttpResponseBuilder::new(cache_value.status)
107112
.append_header((
108113
ETAG,
109114
base16ct::lower::encode_string(cache_value.etag.as_ref())
@@ -145,13 +150,17 @@ pub async fn middleware(
145150
};
146151

147152
let etag: [u8; 32] = Sha256::digest(&bytes).into();
148-
cache
149-
.insert(cache_key, CacheValue {
150-
response: bytes.clone(),
151-
headers: res.headers().to_owned(),
152-
etag
153-
})
154-
.await;
153+
if res.status().is_success() {
154+
// Only cache successful requests to avoid caching errors
155+
cache
156+
.insert(cache_key, CacheValue {
157+
response: bytes.clone(),
158+
headers: res.headers().to_owned(),
159+
status: res.status(),
160+
etag
161+
})
162+
.await;
163+
}
155164

156165
let etag_str = &mut [0u8; 64];
157166
base16ct::lower::encode_str(&etag, etag_str)

0 commit comments

Comments
 (0)