import type { Cache, CacheEvents, FallbackableCacheOptions } from '../types'; import { createNullCache } from './createNullCache'; export function createFallbackableCache(options: FallbackableCacheOptions): Cache { const caches = [...options.caches]; const current = caches.shift(); if (current === undefined) { return createNullCache(); } return { get( key: Record | string, defaultValue: () => Promise, events: CacheEvents = { miss: (): Promise => Promise.resolve(), }, ): Promise { return current.get(key, defaultValue, events).catch(() => { return createFallbackableCache({ caches }).get(key, defaultValue, events); }); }, set(key: Record | string, value: TValue): Promise { return current.set(key, value).catch(() => { return createFallbackableCache({ caches }).set(key, value); }); }, delete(key: Record | string): Promise { return current.delete(key).catch(() => { return createFallbackableCache({ caches }).delete(key); }); }, clear(): Promise { return current.clear().catch(() => { return createFallbackableCache({ caches }).clear(); }); }, }; }