You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
835 B
JavaScript
38 lines
835 B
JavaScript
'use strict';
|
|
|
|
const Promise = require("bluebird");
|
|
|
|
/* NOTE: This assumes that the first argument to the cacheized call, will be
|
|
* the cache key. */
|
|
|
|
module.exports = function(cache, cb) {
|
|
function getFromRemote(...args) {
|
|
return Promise.try(() => {
|
|
return cb(...args);
|
|
}).tap((result) => {
|
|
cache.set(args[0], Object.assign({
|
|
$cacheKey: args[0]
|
|
}, result));
|
|
});
|
|
}
|
|
|
|
function getFromCache(...args) {
|
|
return Promise.try(() => {
|
|
return cache.get(args[0]);
|
|
}).then((metadata) => {
|
|
if (metadata._cacheExpiry < Date.now()) {
|
|
throw new cache.CacheError("Cached data expired");
|
|
} else {
|
|
return metadata;
|
|
}
|
|
});
|
|
}
|
|
|
|
return function(...args) {
|
|
return Promise.try(() => {
|
|
return getFromCache(...args);
|
|
}).catch(cache.CacheError, (err) => {
|
|
return getFromRemote(...args);
|
|
});
|
|
}
|
|
} |