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.
- ttl
Seconds a stored success stays fresh.
NULL, the default, means the configured lifetime fromBIOHTTP_CACHE_TTL. Pass a longer one for a bulk file that should outlive the ordinary lookups around it. The disk tier's ownBIOHTTP_CACHE_DISK_TTLstill caps it.
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
#>
#> $retry_after
#> [1] NA
#>
#> $ts
#> [1] "2026-09-16 15:01:37 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
#>
#> $retry_after
#> [1] NA
#>
#> $ts
#> [1] "2026-09-16 15:01:37 UTC"
#>
# A bulk table that is worth keeping for a day.
big <- cache_key("demo", "GET_TEXT /table.tsv")
cached(big, function() status_ok(data = "a\tb\n"), ttl = 86400)
#> $ok
#> [1] TRUE
#>
#> $status
#> [1] "ok"
#>
#> $http
#> [1] 200
#>
#> $data
#> [1] "a\tb\n"
#>
#> $source
#> [1] "API"
#>
#> $error
#> NULL
#>
#> $detail
#> NULL
#>
#> $retry_after
#> [1] NA
#>
#> $ts
#> [1] "2026-09-16 15:01:37 UTC"
#>