import type { SchedulerFn } from './scheduler' import { DetachedPromise } from './detached-promise' type CacheKeyFn = ( key: K ) => PromiseLike | C type BatcherOptions = { cacheKeyFn?: CacheKeyFn schedulerFn?: SchedulerFn } type WorkFn = ( key: C, resolve: (value: V | PromiseLike) => void ) => Promise /** * A wrapper for a function that will only allow one call to the function to * execute at a time. */ export class Batcher { private readonly pending = new Map>() protected constructor( private readonly cacheKeyFn?: CacheKeyFn, /** * A function that will be called to schedule the wrapped function to be * executed. This defaults to a function that will execute the function * immediately. */ private readonly schedulerFn: SchedulerFn = (fn) => fn() ) {} /** * Creates a new instance of PendingWrapper. If the key extends a string or * number, the key will be used as the cache key. If the key is an object, a * cache key function must be provided. */ public static create( options?: BatcherOptions ): Batcher public static create( options: BatcherOptions & Required, 'cacheKeyFn'>> ): Batcher public static create( options?: BatcherOptions ): Batcher { return new Batcher(options?.cacheKeyFn, options?.schedulerFn) } /** * Wraps a function in a promise that will be resolved or rejected only once * for a given key. This will allow multiple calls to the function to be * made, but only one will be executed at a time. The result of the first * call will be returned to all callers. * * @param key the key to use for the cache * @param fn the function to wrap * @returns a promise that resolves to the result of the function */ public async batch(key: K, fn: WorkFn): Promise { const cacheKey = (this.cacheKeyFn ? await this.cacheKeyFn(key) : key) as C if (cacheKey === null) { return fn(cacheKey, Promise.resolve) } const pending = this.pending.get(cacheKey) if (pending) return pending const { promise, resolve, reject } = new DetachedPromise() this.pending.set(cacheKey, promise) this.schedulerFn(async () => { try { const result = await fn(cacheKey, resolve) // Resolving a promise multiple times is a no-op, so we can safely // resolve all pending promises with the same result. resolve(result) } catch (err) { reject(err) } finally { this.pending.delete(cacheKey) } }) return promise } }