responseCache
An object that allows direct read and write access to the response cache.
import { responseCache } from 'bestfetch';
responseCache
has the following methods:
get
Retrieve the cached response for a given requestKey
.
requestKey
: The request key of the response to retrieve from the cache.A response
, if one exists. If no response exists in the cache for the specified requestKey
, then undefined
will be returned instead.
responseCache.get('my-request-key');
set
Set the cached response
for a particular requestKey
.
requestKey
: The request key of the request.response
: The response to associate with the requestKey
.The responseCache
object.
responseCache.set('my-request-key', response);
has
Used to determine if a response exists in the cache for requestKey
.
requestKey
: The requestKey
to check.A boolean
representing whether or not a response exists in the cache for requestKey
.
responseCache.has('my-request-key');
delete
Used to delete a response from the cache for requestKey
.
requestKey
: The requestKey
to delete from the cache.A boolean
that is true
when a response was found and deleted from the cache, and false
when a response did not exist in the cache.
responseCache.delete('my-request-key');
clear
Removes all responses from the cache.
This method does not accept any arguments.
This method does not return anything.
responseCache.clear();
useCachedResponse
Configure the invalidation strategy for your application. You should only call this method one time, when your app first loads.
cacheInvalidationPolicy
: A function that defines your invalidation policy. Each time that the cache would be hit, this function will be called. It is passed a single argument: cacheObject
. Return true
to use the cached object, or false
to invalidate it.A cacheObject
has the following shape:
createdAt
: A timestamp (in milliseconds) when the response was added to the cache.lastAccessedAt
: A timecode (in milliseconds) when this response was last read from the cache.accessCount
: How many times the response has been read from the cache.res
: The cached response.This method does not return anything.
// 1000 = 1 second in milliseconds
// * 60 = 1 minute
// * 10 = 10 minutes
const TEN_MINUTES = 1000 * 60 * 10;
responseCache.useCachedResponse(cacheObject => {
const currentTimestamp = Date.now();
return currentTimestamp - cacheObject.createdAt <= TEN_MINUTES;
});
For more on how to use this method, refer to the Invalidating the Cache guide.