import nullthrows from '@expo/nullthrows'; import type { ISecondaryEntityCache } from './EntitySecondaryCacheLoader.ts'; /** * A ISecondaryEntityCache that composes other ISecondaryEntityCache instances. */ export class ComposedSecondaryEntityCache< TLoadParams, TFields extends Record, > implements ISecondaryEntityCache { /** * @param secondaryEntityCaches - list of caches to compose in order of precedence. * Earlier caches are read from first and written to (including invalidations) last. * Typically, caches closer to the application should be ordered before caches closer to the database. */ constructor( private readonly secondaryEntityCaches: ISecondaryEntityCache[], ) {} async loadManyThroughAsync( loadParamsArray: readonly Readonly[], fetcher: ( fetcherLoadParamsArray: readonly Readonly[], ) => Promise, Readonly | null>>, ): Promise, Readonly | null>> { return await ComposedSecondaryEntityCache.loadManyThroughRecursivelyAsync( this.secondaryEntityCaches, loadParamsArray, fetcher, ); } private static async loadManyThroughRecursivelyAsync< TLoadParams, TFields extends Record, >( secondaryEntityCaches: ISecondaryEntityCache[], loadParamsArray: readonly Readonly[], fetcher: ( fetcherLoadParamsArray: readonly Readonly[], ) => Promise, Readonly | null>>, ): Promise, Readonly | null>> { if (secondaryEntityCaches.length === 0) { return await fetcher(loadParamsArray); } const [firstCache, ...restCaches] = secondaryEntityCaches; return await nullthrows(firstCache).loadManyThroughAsync( loadParamsArray, (fetcherLoadParamsArray) => ComposedSecondaryEntityCache.loadManyThroughRecursivelyAsync( restCaches, fetcherLoadParamsArray, fetcher, ), ); } async invalidateManyAsync(loadParamsArray: readonly Readonly[]): Promise { // invalidate lower layers first for (let i = this.secondaryEntityCaches.length - 1; i >= 0; i--) { const secondaryEntityCache = nullthrows(this.secondaryEntityCaches[i]); await secondaryEntityCache.invalidateManyAsync(loadParamsArray); } } }