2023-06-19 08:42:29 -05:00
|
|
|
export class CachePromiseFactory <A, R> {
|
2021-06-09 06:34:40 -05:00
|
|
|
private readonly running = new Map<string, Promise<R>>()
|
|
|
|
|
|
|
|
constructor (
|
|
|
|
private readonly fn: (arg: A) => Promise<R>,
|
|
|
|
private readonly keyBuilder: (arg: A) => string
|
|
|
|
) {
|
|
|
|
}
|
|
|
|
|
|
|
|
run (arg: A) {
|
2023-06-19 08:42:29 -05:00
|
|
|
return this.runWithContext(null, arg)
|
|
|
|
}
|
|
|
|
|
|
|
|
runWithContext (ctx: any, arg: A) {
|
2021-06-09 06:34:40 -05:00
|
|
|
const key = this.keyBuilder(arg)
|
|
|
|
|
|
|
|
if (this.running.has(key)) return this.running.get(key)
|
|
|
|
|
2023-06-19 08:42:29 -05:00
|
|
|
const p = this.fn.apply(ctx || this, [ arg ])
|
2021-06-09 06:34:40 -05:00
|
|
|
|
|
|
|
this.running.set(key, p)
|
|
|
|
|
|
|
|
return p.finally(() => this.running.delete(key))
|
|
|
|
}
|
|
|
|
}
|
2023-06-19 08:42:29 -05:00
|
|
|
|
|
|
|
export function CachePromise (options: {
|
|
|
|
keyBuilder: (...args: any[]) => string
|
|
|
|
}) {
|
|
|
|
return function (_target, _key, descriptor: PropertyDescriptor) {
|
|
|
|
const promiseCache = new CachePromiseFactory(descriptor.value, options.keyBuilder)
|
|
|
|
|
|
|
|
descriptor.value = function () {
|
|
|
|
if (arguments.length !== 1) throw new Error('Cache promise only support methods with 1 argument')
|
|
|
|
|
|
|
|
return promiseCache.runWithContext(this, arguments[0])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|