Skip to main content

Cache


Introduction

Cache is responsible for storing response data from the 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 to any other compatible interface.


Purpose

  • Storing requests results
  • Managing stored data
  • Emitting storage events

CacheKey

The cache stores data on a key-value basis. The key is always specified inside the Command as cacheKey, and it determines where the data is stored and it's used for propagation of the data handling events. The cacheKey value is automatically determined by default based on parameters such as the method, endpoint and query params of the given command, but there is nothing to prevent you from adding the key manually when setting the Command 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.

Name Type Description
emitCacheData (cacheKey: string, data: CacheValueType<Response, Error>) => void -
emitRevalidation (cacheKey: string) => void -
onData (cacheKey: string, callback: (data: CacheValueType<Response, Error>) => void) => VoidFunction -
onRevalidate (cacheKey: string, callback: () => void) => VoidFunction -


Storages

By default, the cache uses Map as a data retention location. However, it is possible to replace the place where the data is stored in the system. We can use local storage, indexeddb - no matter if the source works synchronously or asynchronously.

This way we can setup the Persistent storage that will last between sessions.

export const builder = new Builder<ServerErrorType>({
baseUrl: "localhost:3000",
cache: (instance) =>
new Cache(instance, {
storage,
}),
});

Persistence

We can achieve the persistence of the stored data by changing the cache storage to persistent one. It needs to match the provided interface.

Read More

info

Currently there is no cross tabs synchronization. It's planned for next releases when we will have more insights from our internal testing.


Lifecycle

Cache options can be provided with some lifecycle methods. These are events such as onInitialization.


Parameters

Configuration options

Name Type Description
clearKey string Key to clear lazy storage data
lazyStorage CacheAsyncStorageType Lazy loading from remote resources - possibly persistent
storage CacheStorageType Assign your custom sync storage
onChange (key: string, data: CacheValueType<Response, Error>) => void Callback for every change in the storage
onDelete (key: string) => void Callback for every delete in the storage
onInitialization (cache: Cache) => void Initialization callback