UNPKG

@botonic/plugin-contentful

Version:

Botonic Plugin Contentful is one of the **[available](https://github.com/hubtype/botonic/tree/master/packages)** plugins for Botonic. **[Contentful](http://www.contentful.com)** is a CMS (Content Management System) which manages contents of a great variet

60 lines 2.09 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fallbackStrategy = exports.cacheForeverStrategy = exports.Memoizer = exports.jsonNormalizer = void 0; const tslib_1 = require("tslib"); const cache_1 = require("./cache"); const jsonNormalizer = (...args) => { return JSON.stringify(args); }; exports.jsonNormalizer = jsonNormalizer; class Memoizer { constructor(opts) { this.opts = { strategy: opts.strategy, normalizer: opts.normalizer || exports.jsonNormalizer, cacheFactory: opts.cacheFactory || (() => new cache_1.InMemoryCache()), }; } memoize(func) { const cache = this.opts.cacheFactory(); const f = (...args) => this.opts.strategy(cache, this.opts.normalizer, func, ...args); return f; } } exports.Memoizer = Memoizer; /*** * Only re-invoke if not in cache */ const cacheForeverStrategy = (cache, normalizer = exports.jsonNormalizer, func, ...args) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { const id = normalizer(...args); let val = cache.get(id); if (val === cache_1.NOT_FOUND_IN_CACHE) { val = yield func(...args); cache.set(id, val); } return val; }); exports.cacheForeverStrategy = cacheForeverStrategy; /** * Always invokes the function, but fallbacks to last invocation result if available */ function fallbackStrategy(usingFallback) { return (cache, normalizer = exports.jsonNormalizer, func, ...args) => tslib_1.__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 !== cache_1.NOT_FOUND_IN_CACHE) { yield usingFallback(String(func.name), args, e); return oldVal; } throw e; } }); } exports.fallbackStrategy = fallbackStrategy; //# sourceMappingURL=memoizer.js.map