From 8faa7ddc01f10d1d5bf2d91254f73f03c286312a Mon Sep 17 00:00:00 2001 From: Hadley Wickham Date: Fri, 25 Oct 2024 07:30:20 -0500 Subject: [PATCH] Only retrieve GET quieries from cache --- NEWS.md | 1 + R/req-cache.R | 6 ++++++ tests/testthat/test-req-cache.R | 15 +++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/NEWS.md b/NEWS.md index 554ae975..73421b88 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,7 @@ # httr2 1.0.5 +* `req_cache()` no longer retrieves anything but `GET` requests from the cache. * New `resp_stream_aws()` to retrieve AWS's special streaming format. With thanks to for a simple reference implementation. * New `req_auth_aws_v4()` signs request using AWS's special format (#562, #566). * `req_perform_parallel()` and `req_perform_promise()` now correctly set up the method and body (#549). diff --git a/R/req-cache.R b/R/req-cache.R index 7be568cd..f92ab9ad 100644 --- a/R/req-cache.R +++ b/R/req-cache.R @@ -186,6 +186,12 @@ cache_pre_fetch <- function(req, path = NULL) { return(req) } + # Only GET requests should be retrieved from cache. It's not sufficient to + # only save GET requests, because the method is not part of the cache key + if (req_method_get(req) != "GET") { + return(req) + } + debug <- cache_debug(req) cache_prune_if_needed(req, debug = debug) diff --git a/tests/testthat/test-req-cache.R b/tests/testthat/test-req-cache.R index a77d7d57..9dc1a74f 100644 --- a/tests/testthat/test-req-cache.R +++ b/tests/testthat/test-req-cache.R @@ -6,6 +6,21 @@ test_that("nothing happens if cache not enabled", { expect_equal(cache_post_fetch(req, resp), resp) }) +test_that("never retrieves POST request from cache", { + req <- request("http://example.com") %>% + req_method("POST") %>% + req_cache(tempfile()) + + # Fake an equivalent GET request in the cache + resp <- response(200, + headers = "Expires: Wed, 01 Jan 3000 00:00:00 GMT", + body = charToRaw("abc") + ) + cache_set(req, resp) + + expect_equal(cache_pre_fetch(req), req) +}) + test_that("immutable objects retrieved directly from cache", { req <- request("http://example.com") %>% req_cache(tempfile()) resp <- response(200,