Skip to content

Commit

Permalink
feat(lib): let storage handle ttl
Browse files Browse the repository at this point in the history
  • Loading branch information
AlaaZorkane committed Apr 21, 2024
1 parent 52c39d3 commit ecafe1b
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 20 deletions.
21 changes: 1 addition & 20 deletions lib/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,8 @@ import "reflect-metadata";

export const cacheEventEmitter = new EventEmitter();
export const intervalTimerMap = new Map<string, boolean>();
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;

Expand Down Expand Up @@ -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;
};
Expand Down
1 change: 1 addition & 0 deletions lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export type CacheOptions<Kind extends CacheKind> = 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<boolean>;
has(key: string): boolean | Promise<boolean>;
}

0 comments on commit ecafe1b

Please sign in to comment.