⭐️ bestfetch

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.

Arguments

  1. requestKey: The request key of the response to retrieve from the cache.

Returns

A response, if one exists. If no response exists in the cache for the specified requestKey, then undefined will be returned instead.

Example Usage

responseCache.get('my-request-key');

set

Set the cached response for a particular requestKey.

Arguments

  1. requestKey: The request key of the request.
  2. response: The response to associate with the requestKey.

Returns

The responseCache object.

Example Usage

responseCache.set('my-request-key', response);

has

Used to determine if a response exists in the cache for requestKey.

Arguments

  1. requestKey: The requestKey to check.

Returns

A boolean representing whether or not a response exists in the cache for requestKey.

Example Usage

responseCache.has('my-request-key');

delete

Used to delete a response from the cache for requestKey.

Arguments

  1. requestKey: The requestKey to delete from the cache.

Returns

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.

Example Usage

responseCache.delete('my-request-key');

clear

Removes all responses from the cache.

Arguments

This method does not accept any arguments.

Returns

This method does not return anything.

Example Usage

responseCache.clear();

useCachedResponse

Configure the invalidation strategy for your application. You should only call this method one time, when your app first loads.

Arguments

  1. 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.

Returns

This method does not return anything.

Example Usage

// 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.