$ npm install cache-puppy
import { CachePuppy } from 'cache-puppy';
import axios from 'axios';
const fetchPets = async (): Promise<IPet[]> => {
return (await axios.get('www.pets/api/puppies')).data;
};
// cached pets with revalidation every 5 minutes
const cache = new CachePuppy<IPet[]>({
initialData: fetchPets,
revalidateFn: fetchPets,
fallbackFn: [
{ petId: 23, name: 'bulldog' },
{ petId: 18, name: 'yorkshire terrier' },
],
revalidateOpts: {
retries: 5,
interval: 1000 * 60 * 5, // 5 mins
},
});
// some time later
console.log(cache.get()); // cached pets
- Simple to the point interface
- Linear and exponential retry strategies
- Provides custom Initial data, Revalidate and Fallback resolvers
- Allows plugging in custom cache setters/getters (can be useful for using other in memory caching connectors e.g Redis, Memcached)
Property | Type | description |
---|---|---|
get | () => T |
gets cache value |
set | (data: T) => Promise<void> |
sets cache value |
revalidate | () => Promise< void > |
revalidates cache |
teardown | () => void |
gracfully tears down cache |
An object type representing cache options
Property | Type | description | default |
---|---|---|---|
initialData? | (() => T | Promise< T >) | T |
initial cache data or a function to be resolved from | undefined |
revalidateFn? | (() => T | Promise< T >) | T |
revalidation data or a function to be resolved from | undefined |
fallBackFn? | (() => T | Promise< T >) | T |
fallback value or a function to be resolved from | undefined |
getterFn? | () => T | undefined |
custom cache getter function | undefined |
setterFn? | (data) => void |
custom cache setter function | undefined |
revalidateOpts? | RevalidateOpts | revalidation options | defaultCacheOptions.revalidateOpts |
An object cache revalidation options
Property | Type | description | default |
---|---|---|---|
strategy? | linear | exponential |
cache retry strategy | linear |
interval? | number |
cache revalidation interval (ms) | 6000 (1 min) |
backOff? | number |
retry backoff time (ms) | 300 |
exponentialBackoff? | number |
retry exponential backoff time (ms) (for exponential strategy) | 10 |
retries | number |
number of maximum retries | 3 |
onSuccess | (cache) => Promise< void > | void |
callback on revalidation success | undefined |
onRetriesReached | (cache, err) => Promise< void > | void |
callback on maximum retries reached | undefined |
- async getterFn/setterFn
- tests