UNPKG

@botonic/plugin-contentful

Version:

## What Does This Plugin Do?

53 lines 1.72 kB
import { __awaiter } from "tslib"; import { InMemoryCache, NOT_FOUND_IN_CACHE } from './cache'; export const jsonNormalizer = (...args) => { return JSON.stringify(args); }; export class Memoizer { constructor(opts) { this.opts = { strategy: opts.strategy, normalizer: opts.normalizer || jsonNormalizer, cacheFactory: opts.cacheFactory || (() => new InMemoryCache()), }; } memoize(func) { const cache = this.opts.cacheFactory(); const f = (...args) => this.opts.strategy(cache, this.opts.normalizer, func, ...args); return f; } } /*** * Only re-invoke if not in cache */ export const cacheForeverStrategy = (cache, normalizer = jsonNormalizer, func, ...args) => __awaiter(void 0, void 0, void 0, function* () { const id = normalizer(...args); let val = cache.get(id); if (val === NOT_FOUND_IN_CACHE) { val = yield func(...args); cache.set(id, val); } return val; }); /** * Always invokes the function, but fallbacks to last invocation result if available */ export function fallbackStrategy(usingFallback) { return (cache, normalizer = jsonNormalizer, func, ...args) => __awaiter(this, void 0, void 0, function* () { const id = normalizer(...args); const oldVal = cache.get(id); try { const newVal = yield func(...args); cache.set(id, newVal); return newVal; } catch (e) { if (oldVal !== NOT_FOUND_IN_CACHE) { yield usingFallback(String(func.name), args, e); return oldVal; } throw e; } }); } //# sourceMappingURL=memoizer.js.map