'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); }); } }