UNPKG

@botonic/plugin-contentful

Version:

## What Does This Plugin Do?

41 lines 2.24 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FallbackCachedClientApi = void 0; const cache_1 = require("../../util/cache"); const memoizer_1 = require("../../util/memoizer"); /** * Use memoization to remember forever the last successful result, and use it * whenever Contentful fails. */ class FallbackCachedClientApi { constructor(client, cacheLimitKB, reporter, logger = console.error) { this.numRecoveredErrors = 0; this.numMemoizations = 0; // TODO share the same cache for all APIs to avoid reaching a Memoizer limit // while others have empty space const memoizerCache = () => new cache_1.LimitedCacheDecorator(new cache_1.InMemoryCache(), cacheLimitKB / FallbackCachedClientApi.NUM_APIS, logger); // We could maybe use a more optimal normalizer than jsonNormalizer // (like they do in fast-json-stringify to avoid JSON.stringify for functions with a single nulls, numbers and booleans). // But it's not worth since stringify will have a cost much lower than constructing/rendering a botonic component // (and we're already optimizing the costly call to CMS) this.memoizer = new memoizer_1.Memoizer({ cacheFactory: memoizerCache, strategy: (0, memoizer_1.fallbackStrategy)((f, args, e) => reporter(`Successfully used cached fallback after Contentful API error`, f, args, e)), }); this.getAsset = this.memoize(client.getAsset.bind(client)); this.getAssets = this.memoize(client.getAssets.bind(client)); this.getEntries = this.memoize(client.getEntries.bind(client)); this.getEntry = this.memoize(client.getEntry.bind(client)); this.getContentType = this.memoize(client.getContentType.bind(client)); if (this.numMemoizations != FallbackCachedClientApi.NUM_APIS) { throw new Error('FallbackCachedClientApi.NUM_APIS must equal the number of memoized APIs'); } } memoize(func) { this.numMemoizations++; return this.memoizer.memoize(func); } } exports.FallbackCachedClientApi = FallbackCachedClientApi; FallbackCachedClientApi.NUM_APIS = 5; //# sourceMappingURL=fallback-cache.js.map