@newdash/newdash
Version:
javascript/typescript utility library
47 lines (46 loc) • 1.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fallbackCache = void 0;
// @ts-nocheck
const assert_1 = require("../assert");
const cacheProvider_1 = require("../cacheProvider");
const functionWrapper_1 = require("../functional/functionWrapper");
const toHashCode_1 = require("../functional/toHashCode");
/**
* fallback to cache, if runner throw error, will try to return the latest cached value
*
* @since 5.15.0
* @category Fallback
*
* @param runner
* @param cacheSize the maximum number cache item (different parameters)
*/
function fallbackCache(runner, cacheSize = 1024) {
(0, assert_1.mustProvide)(runner, "runner", "function");
return (0, functionWrapper_1.createFunctionWrapper)(runner, {
global: { funcCache: new cacheProvider_1.LRUCacheProvider(cacheSize) },
before: (ctx) => {
ctx.state.key = (0, toHashCode_1.toHashCode)(ctx.args);
},
after: (ctx, result) => {
const cache = ctx.global.funcCache;
const key = ctx.state.key;
if (ctx.state?.isAsync === true) {
cache.set(key, Promise.resolve(result));
}
else {
cache.set(key, result);
}
return result;
},
error: (ctx, error) => {
const cache = ctx.global.funcCache;
const key = ctx.state.key;
if (cache.has(key)) {
return cache.get(key);
}
throw error;
}
});
}
exports.fallbackCache = fallbackCache;