import {createAsyncCacheMap} from './CacheMapImplementation'; import {AsyncCacheMap, CacheMapInput} from './types'; export interface DedupedAsyncFunction { (key: TKey): Promise; cache: AsyncCacheMap; } export interface DedupeAsyncOptionsWithMapKey { cache?: CacheMapInput>; mapKey: (key: TKey) => TMappedKey; shouldCache?: (value: TResult, key: TKey) => boolean; } export interface DedupeAsyncOptionsWithoutMapKey { cache?: CacheMapInput>; mapKey?: undefined; shouldCache?: (value: TResult, key: TKey) => boolean; } export interface DedupeAsyncOptionsWithCache { cache: CacheMapInput>; mapKey?: undefined; shouldCache?: (value: TResult, key: TKey) => boolean; } export type DedupeAsyncOptions = | DedupeAsyncOptionsWithMapKey | DedupeAsyncOptionsWithoutMapKey; /** * dedupeAsync wraps a function that returns a Promise and deduplicates * calls to the function with the same key. */ export default function dedupeAsync( fn: (key: TKey) => Promise, options?: DedupeAsyncOptions, ): DedupedAsyncFunction { const {cache, mapKey, shouldCache} = normalizeDedupeAsyncOptions(options); return Object.assign( async (key: TKey): Promise => { const cacheKey = mapKey(key); const cached = cache.get(cacheKey); if (cached !== undefined) return cached; const fresh = fn(key).then( (result) => { if (!shouldCache(result, key)) { cache.delete(cacheKey); } return result; }, (ex) => { cache.delete(cacheKey); throw ex; }, ); cache.set(cacheKey, fresh); return fresh; }, {cache: createAsyncCacheMap(cache, mapKey)}, ); } interface NormalizedDedupeAsyncOptions { cache: CacheMapInput>; mapKey: (key: TKey) => TMappedKey; shouldCache: (value: TResult, key: TKey) => boolean; } const identityFn = (arg: T): T => arg; const trueFn = (): true => true; function normalizeDedupeAsyncOptions( options?: DedupeAsyncOptions, ): NormalizedDedupeAsyncOptions { return { // @ts-expect-error If not using mapKey, then TMappedKey is TKey cache: options?.cache ?? new Map(), // @ts-expect-error If not using mapKey, then TMappedKey is TKey mapKey: options?.mapKey ?? identityFn, shouldCache: options?.shouldCache ?? trueFn, }; }