From c3bcc75e883bada2731977c42cf169fbf88db148 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 20 Nov 2024 17:40:35 -0500 Subject: [PATCH] Refactor to guard --- server/utils/CacheHelper.ts | 57 +++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/server/utils/CacheHelper.ts b/server/utils/CacheHelper.ts index 4ec08a953d..441de236f6 100644 --- a/server/utils/CacheHelper.ts +++ b/server/utils/CacheHelper.ts @@ -26,35 +26,36 @@ export class CacheHelper { ): Promise { let cache = await this.getData(key); - // Nothing in the cache, acquire a lock to prevent multiple writes - if (!cache) { - let lock; - const lockKey = `lock:${key}`; - try { - try { - lock = await MutexLock.lock.acquire( - [lockKey], - MutexLock.defaultLockTimeout - ); - } catch (err) { - Logger.error(`Could not acquire lock for ${key}`, err); - } - cache = await this.getData(key); - if (cache) { - return cache; - } - - // Get the data from the callback and save it in cache - const value = await callback(); - if (value) { - await this.setData(key, value, expiry); - } - return value; - } finally { - await lock?.release(); - } + if (cache) { + return cache; + } + + // Nothing in the cache, acquire a lock to prevent multiple writes + let lock; + const lockKey = `lock:${key}`; + try { + try { + lock = await MutexLock.lock.acquire( + [lockKey], + MutexLock.defaultLockTimeout + ); + } catch (err) { + Logger.error(`Could not acquire lock for ${key}`, err); + } + cache = await this.getData(key); + if (cache) { + return cache; + } + + // Get the data from the callback and save it in cache + const value = await callback(); + if (value) { + await this.setData(key, value, expiry); + } + return value; + } finally { + await lock?.release(); } - return cache; } /**