aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers
diff options
context:
space:
mode:
Diffstat (limited to 'server/helpers')
-rw-r--r--server/helpers/promise-cache.ts22
1 files changed, 20 insertions, 2 deletions
diff --git a/server/helpers/promise-cache.ts b/server/helpers/promise-cache.ts
index 07e8a9962..303bab976 100644
--- a/server/helpers/promise-cache.ts
+++ b/server/helpers/promise-cache.ts
@@ -1,4 +1,4 @@
1export class PromiseCache <A, R> { 1export class CachePromiseFactory <A, R> {
2 private readonly running = new Map<string, Promise<R>>() 2 private readonly running = new Map<string, Promise<R>>()
3 3
4 constructor ( 4 constructor (
@@ -8,14 +8,32 @@ export class PromiseCache <A, R> {
8 } 8 }
9 9
10 run (arg: A) { 10 run (arg: A) {
11 return this.runWithContext(null, arg)
12 }
13
14 runWithContext (ctx: any, arg: A) {
11 const key = this.keyBuilder(arg) 15 const key = this.keyBuilder(arg)
12 16
13 if (this.running.has(key)) return this.running.get(key) 17 if (this.running.has(key)) return this.running.get(key)
14 18
15 const p = this.fn(arg) 19 const p = this.fn.apply(ctx || this, [ arg ])
16 20
17 this.running.set(key, p) 21 this.running.set(key, p)
18 22
19 return p.finally(() => this.running.delete(key)) 23 return p.finally(() => this.running.delete(key))
20 } 24 }
21} 25}
26
27export function CachePromise (options: {
28 keyBuilder: (...args: any[]) => string
29}) {
30 return function (_target, _key, descriptor: PropertyDescriptor) {
31 const promiseCache = new CachePromiseFactory(descriptor.value, options.keyBuilder)
32
33 descriptor.value = function () {
34 if (arguments.length !== 1) throw new Error('Cache promise only support methods with 1 argument')
35
36 return promiseCache.runWithContext(this, arguments[0])
37 }
38 }
39}