Cache
Introduction
Cache
stores response data from requests. It uses an event system that successively transmits data and takes care
of validation in the system. Data is stored under cacheKey
in the storage (which by default is a Map object, but can
be replaced by any other compatible interface).
Purpose
- Stores request results
- Manages stored data
- Emits storage events
CacheKey
The cache stores data on a key-value
basis. The key is always specified inside the request as cacheKey
; it
determines where the data is stored and is used in propagation of data handling events.
By default, the cacheKey value is auto-determined based on the method, endpoint, and query params of the given request. However, there is nothing to prevent you manually adding the key when setting the request or using one of its methods.
Thanks to the automatic way of indexing data in the cache, we do not have to worry about paginated keys in the data – everything will happen automatically.
Events
Available cache events.
{
emitCacheData: (cacheKey: string, data: CacheValueType<Response, Error, Adapter>) => void;
emitRevalidation: (cacheKey: string) => void;
onData: (cacheKey: string, callback: (data: CacheValueType<Response, Error, Adapter>) => void) => VoidFunction;
onRevalidate: (cacheKey: string, callback: () => void) => VoidFunction;
}
Storage
By default, the cache uses Map as a data retention location. However, you can also choose where the data is stored in the system – i.e. local storage or IndexedDB – regardless if the source works synchronously or asynchronously. This allows you to set up persistent storage across sessions.
export const client = new Client<ServerErrorType>({
url: "localhost:3000",
cache: (instance) =>
new Cache(instance, {
storage,
}),
});
Persistence
We can achieve the persistence of stored data by changing the cache storage to persistent. It must match the provided interface.
Read More
Currently there is no cross-tab synchronization. It's planned for a future release.
Lifecycle
Cache options can be provided with some lifecycle methods. These are events such as onInitialization
.
Parameters
Configuration options
{
clearKey: string;
lazyStorage: {
delete: (key: string) => Promise<void>;
get: (key: string) => Promise<CacheValueType<Response, Error, Adapter> | undefined>;
keys: () => Promise<string[] | IterableIterator<string> | string[]>;
set: (key: string, data: CacheValueType<Response, Error, Adapter>) => Promise<void>;
};
onChange: (key: string, data: CacheValueType<Response, Error, Adapter>) => void;
onDelete: (key: string) => void;
onInitialization: (cache: Cache<C>) => void;
storage: {
clear: () => void;
delete: (key: string) => void;
get: (key: string) => CacheValueType<Response, Error, Adapter> | undefined;
keys: () => string[] | IterableIterator<string> | string[];
set: (key: string, data: CacheValueType<Response, Error, Adapter>) => void;
};
}