Cache with Resolver
Function based cache storage built around Map-like object.
Typed for TypeScript
npm install --save cache-with-resolver
Why?
Usually when working with cache storages, the storage itself operates only with get
and set
methods. This storage can also operate with functions.
Getting started
CachedControl
constructor can be passed config object containing default TimeToLive (otherwise 3600 seconds if not specified in resolve
method) and custom Map
-like object (has to implement Map
's methods and properties). Custom Map
can be used to share cahces between multiple CacheControl
s.
Methods resolve
and resolveSync
take up to three arguments key
, function to resolve
and time to live
. First two arguments are mandatory.
// ES6
import CacheControl from 'cache-with-resolver';
// CommonJS
const CacheControl = require('cache-with-resolver').default;
let cacheControl = new CacheControl();
...
async function GetUserFromDb(id) {
return cacheControl.resolve('user' + id, cache => {
db.query(...).then(userObject => {
cache(userOBject);
});
})
}
Function that contains code to be cached follows similar pattern to function passed to Promise
constructor. It is given one argument, callback function called cache
that is passed a value to be cached. This allows to encapsulate logic in Promise
-like fashion.
As long as cached value doesn't pass it's time to live, passed function wont be invoked, instead cached value will be directly returned.
Whenever a cached object is to be retunred, it's deep cloned in order to prevent mutation.
TimeToLive is always in seconds.
resolve
method return Promise
that resolves to cached value. Promise
is returned as async functions may be invoked inside passed function. resolveSync
return cached value directly thus using async functions inside passed function will lead to unwanted behaviour.
Reference
CacheControl
Properties
length
- getter, number of alive cachesentries
- getter, array of tuples[key, value]
of alive caches
Methods
drop()
- drop all cachesdelete(key)
- delete cache of the keyfilteredDelete({ olderThan?: Date, newerThan?: Date})
- delete chaces based on creation timehas(key)
- returns true if cache of the key exists, otherwise falseget(key)
- returns cached value or null (if doesnt exist)set(key, value, timeToLive)
- creates new cacheresolve(key, func: (cs: (val: any) => void) => void, timeToLive) => Promise
- returns cahced value or runs function and create new chaceresolveSync(key, func: (cs: (val: any) => void) => void, timeToLive) => any
- returns cahced value or runs function and create new chace
CacheControlConfig
timeToLive
- default duration of the cache in secondscacheMap
- customMap
-like object to store caches in