Caches a promise-returning function with a stale-while-revalidate strategy, popularized by the HTTP Cache-Control Extensions for Stale Content (RFC 5861).
It is like the SWR React hook
but for backend development.
Every time the wrapper function is called, if there is no data in the cache or if the age of the data is too old, new data will be fetched and returned. If the age of the data is greater than the revalidation threshold but still valid (stale), it will be returned and new data will be fetched in the background. If several revalidation actions are triggered in parallel, it is guaranteed that only one single call to the wrapped function (per cache key) will be executed. If the data is below the revalidation threshold, it is fresh and is returned right away.
npm install promise-swr
const { setTimeout } = require('node:timers/promises')
const pSwr = require('promise-swr')
const cachedFn = pSwr(asyncCall)
cachedFn()
.then(function (value) {
// `asyncCall` was called and it returned `value`.
})
.then(() => cachedFn())
.then(function (value) {
// The last `value` is returned right away, while `asyncCall` is called in
// the background so the next call returns fresh data.
})
.then(() => setTimeout(SOME_TIME))
.then(() => cachedFn())
.then(function (value) {
// Now `value` is fresh again.
})
Returns an function.
Type: Function
A function.
Type: object
Type: object
Default: new Map()
The cache storage.
Must implement these methods: has(key)
, set(key, value)
, get(key)
and delete(key)
Type: number
Default: Infinity
The maximum time in milliseconds to keep a value in the cache.
Type: Function
Default: (...args) => args[0]
Determines how the caching key will be computed. By default, it will only consider the first argument and use strict equality to evaluate a match.
Type: number
Default: 0
The maximum time in milliseconds to consider a value fresh. After this time, the value will be returned but a revalidation action will be triggered to freshen the cache.
The cached version of fn
.
See How it works above.