aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/promise-cache.ts
blob: 303bab976211654334e3d755d94f23ed775e73d9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
export class CachePromiseFactory <A, R> {
  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) {
    return this.runWithContext(null, arg)
  }

  runWithContext (ctx: any, arg: A) {
    const key = this.keyBuilder(arg)

    if (this.running.has(key)) return this.running.get(key)

    const p = this.fn.apply(ctx || this, [ arg ])

    this.running.set(key, p)

    return p.finally(() => this.running.delete(key))
  }
}

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])
    }
  }
}