utility-http-front-cache
v1.5.0
Published
## Motivation
Downloads
147
Readme
http front cache
Motivation
The http-front-cache
utility was created to provide a simple and efficient way to cache the results of service functions in the browser's session storage. This can significantly improve the performance of applications by reducing the number of redundant network requests and computations. However, it is important to use this utility with caution and adhere to the following constraints:
- The data to be cached is not too big.
- The data to be cached is not sensitive.
- The data to be cached does not change too often.
- The cache does not need to be updated based on user navigation (e.g., caching cart data is not recommended as the user can add more products and the cache will not be updated).
- The service parameters do not change too often (if they change too often, the cache will not be used).
How to Use
Example
import { cacheOnSessionStorage } from '@open-ish/utility-http-front-cache';
type Params = [string];
type Result = { data: string[] };
const fetchData: ServiceFunction<Params, Result> = async (param: string) => {
const response = await fetch(`https://api.example.com/data?param=${param}`);
return response.json();
};
const cachedFetchData = cacheOnSessionStorage(fetchData, 5 * 60 * 1000); // Cache for 5 minutes
// Usage
cachedFetchData('exampleParam').then((result) => {
console.log(result);
});
Another Storage
Currently, the cacheOnSessionStorage
utility only supports session storage as provider. However, it can be easily extended to support other storage mechanisms such as local storage or indexedDB by using the cacheFactory
function.
import { cacheFactory, ServiceFunction } from '@open-ish/utility-http-front-cache';
const customProvider = {
getItem: (key: string) => Uint8Array; // cacheFactory converts the result from serviceFunction on UInt8Array, so you can assumes that the data returned on getItem is always a UInt8Array. Example of provider here https://github.com/open-ish/utility/blob/c6d98898bbc6119cd482b736f57ec897443e71de/packages/http-front-cache/src/lib/providers/session-storage.ts#L1-L8
setItem: (key: string, value: Uint8Array) => void;
removeItem: (key: string) => void;
};
export const cacheOnMyCustomProvider = <TParams extends unknown[], TResult>(
serviceFunction: ServiceFunction<TParams, TResult>,
expire: number
): ServiceFunction<TParams, TResult> => {
return async (...params: TParams): Promise<TResult> => {
return cacheFactory<TParams, TResult>({
params,
expire,
serviceFunction: fetchData,
provider: customProvider,
});
};
};
// usage
const cachedFetchData = cacheOnMyCustomProvider(fetchData, 5 * 60 * 1000); // Cache for 5 minutes
cachedFetchData('exampleParam').then((result) => {
console.log(result);
});