From 4ead40e7766f5964ecd9a11766ff56b95090fe1c Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 9 Jun 2021 13:34:40 +0200 Subject: Cache refresh actor promise --- server/helpers/promise-cache.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 server/helpers/promise-cache.ts (limited to 'server/helpers') diff --git a/server/helpers/promise-cache.ts b/server/helpers/promise-cache.ts new file mode 100644 index 000000000..07e8a9962 --- /dev/null +++ b/server/helpers/promise-cache.ts @@ -0,0 +1,21 @@ +export class PromiseCache { + private readonly running = new Map>() + + constructor ( + private readonly fn: (arg: A) => Promise, + private readonly keyBuilder: (arg: A) => string + ) { + } + + run (arg: A) { + const key = this.keyBuilder(arg) + + if (this.running.has(key)) return this.running.get(key) + + const p = this.fn(arg) + + this.running.set(key, p) + + return p.finally(() => this.running.delete(key)) + } +} -- cgit v1.2.3