Memoize promise-returning functions in memory or using redis. Includes cache expire and prefetch.
npm install @regosinc/memoize-redis
> Memoize promise-returning functions. Includes cache expire and prefetch.
- When data expire mode enabled, new values are fetched in advance. Cache
will be always valid, without "gaps".
- Prefetch happens only for items in use. Inactive ones will be GC-ed as usual.
- Errors are not cached
- You still can enable cache with separate expire time for errors, to avoid
specific peak loads. For example, set 120s for good result and 1s on fail.
``bash`
npm install promise-memoize --save
(\*) IE9 and below will require setTimeout polyfill
for correct work.
`js
// Pseudo code
let db = require('mongoose').createConnection('mongodb://localhost/forum');
function lastPosts(limit) {
return db.model('Post').find().limit(limit).orderBy('-_id').lean(true).exec(); // <- Promise
}
let cachedLastPosts = require('promise-memoize')(lastPosts, { maxAge: 60000 });
// Later...
cachedLastPosts(10).then(posts => console.log(posts));
`
Memoize function fn.
- fn(params...) — function, returning a promise (or any "thenable").
It can have any number of arguments, but arguments should be uniquely
castable to strings (see below).
- options — options for memoization (optional)
- maxAge — an amount of milliseconds it should cache resolved
values for (default: 600, i.e. cache 10 minutes).0
- maxErrorAge — an amount of milliseconds it should cache
rejected values for (default: , i.e. don't cache).fn
- resolve — serialiser to build unique key from arguments.simple
(default: ). Possible values:simple
- (string) — convert each param to string & join those.json
- (string) — JSON.stringify each param & join results.fn
- function(Array) — custom function, with params as array on input[ String, Boolean, 'json', function ]
- — array with custom functions,fn
specific for each param position (text shortcuts as above are allowed).{ type: 'memory' }
- driver - the storage driver that will be used to cache the results (default: ). Available types:memory
- (string) — the cache key/value pairs are stored in memoryredis
- (object) — the cache key/value pairs are stored using redis
- options (object) — the options accepted by the redis client https://www.npmjs.com/package/redis#options-object-properties
Return value is a function with the same signature as fn.
Note. How prefetch works.
If maxAge used and request to cached data happens after 0.7 * maxAge time, then:
- cached data returned
- fn call is executed in parallel
- cached data will be substituted with new one on success, timeouts will be extended.
So your application will not have to wait for data fetch after cache expire.
Returns result as cached promise (errors are not cached by default). If maxAge`
used, tries to prefetch new value before expire to replace cache transparently.
Remove all cached data.