From ecafe1bf7c9d2cff954669959911d52312fecd6f Mon Sep 17 00:00:00 2001 From: Alaa Zorkane Date: Sun, 21 Apr 2024 02:43:47 +0100 Subject: [PATCH] feat(lib): let storage handle ttl --- lib/cache.ts | 21 +-------------------- lib/types.ts | 1 + 2 files changed, 2 insertions(+), 20 deletions(-) diff --git a/lib/cache.ts b/lib/cache.ts index e016c8f..32e6e3a 100644 --- a/lib/cache.ts +++ b/lib/cache.ts @@ -7,18 +7,8 @@ import "reflect-metadata"; export const cacheEventEmitter = new EventEmitter(); export const intervalTimerMap = new Map(); -const timeouts: NodeJS.Timeout[] = []; const intervals: NodeJS.Timeout[] = []; -export function clearAllTimeouts() { - for (const timeout of timeouts) { - clearTimeout(timeout); - } - for (const interval of intervals) { - clearInterval(interval); - } -} - type RootKey = `${string}${typeof ROOT_KEY_SUFFIX}`; const ROOT_KEY_SUFFIX = "__ROOT_KEY__" as const; @@ -172,16 +162,7 @@ export const Cache = const result = await originalMethod.apply(this, args); - storage.set(cacheKey, result); - - const timeout = setTimeout(async () => { - storage.delete(cacheKey); - if (await storage.has(rootKey)) { - deleteChildCacheKey(storage, cacheKey, rootKey); - } - }, ttl * 1000); - - timeouts.push(timeout); + storage.set(cacheKey, result, ttl); return result; }; diff --git a/lib/types.ts b/lib/types.ts index 2b25eb2..e838f64 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -18,6 +18,7 @@ export type CacheOptions = CacheOptionSchema[Kind] & { export interface ICacheStorage { get(key: string): any; set(key: string, value: any): any; + set(key: string, value: any, ttl?: number): any; delete(key: string): boolean | Promise; has(key: string): boolean | Promise; }