-
Notifications
You must be signed in to change notification settings - Fork 194
Closed
Description
I'd like to propose a solution for a common pattern. At least for me.
Usage
const cachedRequest = keyv.memoize(request);
cachedRequest('http://example.com').then(() => { /* result */ });
// later
cachedRequest('http://example.com').then(() => { /* cached result */ });Implementation
/**
* @param {function} func
* @param {object} [opts]
* @param {function} [opts.resolver=identity]
* @param {function|number} [opts.ttl]
* @return {Promise}
*/
Keyv.prototype.memoize = function memoize(func, { resolver, ttl }) {
return (...args) => {
const key = resolver ? resolver(...args) : args[0];
return this.get(key).then((storedValue) => {
if (storedValue !== undefined) {
return storedValue;
}
return Promise.resolve(func(...args)).then((value) => {
if (value !== undefined) {
return this.set(key, value, typeof ttl === 'function' ? ttl(value) : value)
.then(() => value)
;
}
return value;
});
});
};
};Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels