| import type { SchedulerFn } from './scheduler' |
|
|
| import { DetachedPromise } from './detached-promise' |
|
|
| type CacheKeyFn<K, C extends string | number | null> = ( |
| key: K |
| ) => PromiseLike<C> | C |
|
|
| type BatcherOptions<K, C extends string | number | null> = { |
| cacheKeyFn?: CacheKeyFn<K, C> |
| schedulerFn?: SchedulerFn<void> |
| } |
|
|
| type WorkFn<V, C> = ( |
| key: C, |
| resolve: (value: V | PromiseLike<V>) => void |
| ) => Promise<V> |
|
|
| |
| |
| |
| |
| export class Batcher<K, V, C extends string | number | null> { |
| private readonly pending = new Map<C, Promise<V>>() |
|
|
| protected constructor( |
| private readonly cacheKeyFn?: CacheKeyFn<K, C>, |
| |
| |
| |
| |
| |
| private readonly schedulerFn: SchedulerFn<void> = (fn) => fn() |
| ) {} |
|
|
| |
| |
| |
| |
| |
| public static create<K extends string | number | null, V>( |
| options?: BatcherOptions<K, K> |
| ): Batcher<K, V, K> |
| public static create<K, V, C extends string | number | null>( |
| options: BatcherOptions<K, C> & |
| Required<Pick<BatcherOptions<K, C>, 'cacheKeyFn'>> |
| ): Batcher<K, V, C> |
| public static create<K, V, C extends string | number | null>( |
| options?: BatcherOptions<K, C> |
| ): Batcher<K, V, C> { |
| return new Batcher<K, V, C>(options?.cacheKeyFn, options?.schedulerFn) |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public async batch(key: K, fn: WorkFn<V, C>): Promise<V> { |
| 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<V>() |
| this.pending.set(cacheKey, promise) |
|
|
| this.schedulerFn(async () => { |
| try { |
| const result = await fn(cacheKey, resolve) |
|
|
| |
| |
| resolve(result) |
| } catch (err) { |
| reject(err) |
| } finally { |
| this.pending.delete(cacheKey) |
| } |
| }) |
|
|
| return promise |
| } |
| } |
|
|