UNPKG

@botonic/plugin-contentful

Version:

## What Does This Plugin Do?

37 lines 2.07 kB
import { InMemoryCache, LimitedCacheDecorator } from '../../util/cache'; import { fallbackStrategy, Memoizer } from '../../util/memoizer'; /** * Use memoization to remember forever the last successful result, and use it * whenever Contentful fails. */ export 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 LimitedCacheDecorator(new 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({ cacheFactory: memoizerCache, strategy: 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); } } FallbackCachedClientApi.NUM_APIS = 5; //# sourceMappingURL=fallback-cache.js.map