Returns a cached result for key if there is one, otherwise runs fetch()
and stores the result only when it succeeded.
Arguments
- key
A key from
cache_key().- fetch
A function of no arguments returning an envelope.
Details
A failure is never cached. This is the single most important rule in the package. A cache that stores an error fallback poisons itself for the life of the R process, and every later lookup then serves the stored failure instead of retrying. Storing only successes means a transient outage resolves itself the moment the source comes back.
Examples
cache_reset()
key <- cache_key("demo", "GET /x")
cached(key, function() status_ok(data = list(n = 1), source = "demo"))
#> $ok
#> [1] TRUE
#>
#> $status
#> [1] "ok"
#>
#> $http
#> [1] 200
#>
#> $data
#> $data$n
#> [1] 1
#>
#>
#> $source
#> [1] "demo"
#>
#> $error
#> NULL
#>
#> $detail
#> NULL
#>
#> $ts
#> [1] "2026-08-01 08:56:23 UTC"
#>
# A failure runs fetch() again every time.
bad <- cache_key("demo", "GET /y")
cached(bad, function() status_error(source = "demo"))
#> $ok
#> [1] FALSE
#>
#> $status
#> [1] "error"
#>
#> $http
#> [1] NA
#>
#> $data
#> NULL
#>
#> $source
#> [1] "demo"
#>
#> $error
#> [1] "demo is temporarily unavailable. Please try again."
#>
#> $detail
#> NULL
#>
#> $ts
#> [1] "2026-08-01 08:56:23 UTC"
#>