@darkair/api-cache
v1.3.1
Published
This is a small lib on TypeScript to give you an easy way to cache API requests. Instead of caching every API request and solving concurrent event issues, you can write clean, readable code.
Downloads
10
Readme
API Cache
This is a small lib on TypeScript to give you an easy way to cache API requests. Instead of caching every API request and solving concurrent event issues, you can write clean, readable code.
Installation
npm i @darkair/api-cache
Usage
At first, you need to extend the interface ICache
to declare your own properties for caching. Also you have to create ApiCache extends from the class AbstractApiCache
:
import {ICache, AbstractApiCache, CacheValue, CacheArrayValue, makeCacheValue, makeCacheArray} from '@darkair/api-cache';
interface Cache extends ICache {
prop1: CacheValue<User[]>, // Caching single value
prop2: CacheArrayValue<User>, // Caching array of specified values by unique keys
}
class ApiCache extends AbstractApiCache<Cache> {
protected cache: Record<keyof Cache, any> = {
prop1: makeCacheValue<User[]>([]),
prop2: makeCacheArray<User>(null),
};
}
const apiCache: ApiCache = new ApiCache();
export default apiCache;
Next, you can use your apiCache
in your code. For example:
/**
* Get a single value
* Returns User[] or empty array (default value, specified in cache class)
*/
fetchUsers(): Promise<User[]> {
return apiCache.getValue('prop1', async (): Promise<User[]> => {
return fetch('/getUsers')
.then(data => data.json());
});
}
/**
* Get an value of type User from cached array by UNIQ_KEY
* Returns User or null (default value, specified in cache class)
*/
getUser(id: number): Promise<User> {
return apiCache.getArrayValue('prop2', id, async (): Promise<User> => {
return fetch('/getUser', {method: 'post', body: `{"id":${id}}`})
.then(data => data.json());
});
}
Now you can call the methods above when and where you want in your asynchronous code without any unneeded conditions. You will have a guarantee that all of your requests will get the correct data.
// You are guaranteed to have an array with data or empty array
const users: User[] = await fetchUsers();
users.forEach((user: User) => {...});
// Code below send only 5 request (not 5000)
for (let j = 1; j < 1000; j++) {
for (let i = 1; i < 5; i++) {
const user: User = getUser(i);
// Here 'user' will be eather only User or null
}
}
Documentation
Type of single cached value.
interface CacheValue<T>
Type of array with the cached values.
interface CacheArrayValue<T>
Helper function to create the structure for single cached value.
function makeCacheValue<T>(defValue: T): CacheValue<T>
Helper function to create the structure for array with the cached values.
function makeCacheArray<T>(defValue: T): CacheArrayValue<T>
Cache structure interface
interface ICache {
// Your data
}
IApiCache interface
interface IApiCache<TCache extends ICache> {
/**
* Get the value by the key of Cache interface
*/
getValue<T>(name: keyof TCache, func: () => Promise<T>): Promise<T>;
/**
* Get the value of array by the key of Cache interface and uniqKey
*/
getArrayValue<T>(name: keyof TCache, key: string, func: () => Promise<T>): Promise<T>;
/**
* Invalidate the value addressed by the key of Cache interface
*/
invalidate(name: keyof TCache): void;
/**
* Invalidate whole cache
*/
invalidateAll(): void;
/**
* Subscribe to cache invalidation
*/
subscribe(name: keyof TCache, callback: () => void): () => void;
}
Abstract class to extends with your own cache
abstract class AbstractApiCache<TCache extends ICache> implements IApiCache<TCache> {
protected cache: Record<keyof Cache, any> = {
// Your data
}
}