From d9c65bfcd2050a57a8670c4d2deb0bd1635ce7bf Mon Sep 17 00:00:00 2001 From: Steven Spears Date: Wed, 17 Aug 2022 11:14:37 -0400 Subject: [PATCH] Add option to delete cache entry on expiry --- src/index.ts | 19 +++++++++++++++---- test/index.test.ts | 9 +++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/index.ts b/src/index.ts index 4204e4b..0f82323 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,7 @@ export interface FetchParams { params?: any callback(): any expiresInSeconds?: number + deleteOnExpiry?: boolean } export interface KeyParams { @@ -34,13 +35,14 @@ class MapCache implements IStorageCache { key, params = null, callback, - expiresInSeconds = DEFAULT_EXPIRATION_SECONDS + expiresInSeconds = DEFAULT_EXPIRATION_SECONDS, + deleteOnExpiry = false }: FetchParams): Promise { const cacheKey = this.generateKey({ key, params }) const data = this.get(cacheKey) const expiration = this.computeExpirationTime(expiresInSeconds) - return data ? data : this.set({ key: cacheKey, data: await callback(), expiration }) + return data ? data : this.set({ key: cacheKey, data: await callback(), expiration}, deleteOnExpiry, expiresInSeconds) } clear(): void { @@ -76,9 +78,18 @@ class MapCache implements IStorageCache { // Store the data in memory and attach to the object expiration containing the // expiration time. - private set({ key, data, expiration }: StoredData): T { + private set({ key, data, expiration }: StoredData, deleteOnExpiry = false, expiresInSeconds = 0): T { this.cache.set(key, { data, expiration }) + if (deleteOnExpiry && expiresInSeconds > 0) { + setTimeout(() => { + if (this.cache.has(key)) { + this.cache.delete(key) + } + } , expiresInSeconds * 1000) + } + + return data } @@ -87,7 +98,7 @@ class MapCache implements IStorageCache { private get(key: string): T | null { if (this.cache.has(key)) { const { data, expiration } = this.cache.get(key) as StoredData - + return this.hasExpired(expiration) ? null : data } diff --git a/test/index.test.ts b/test/index.test.ts index b3276ab..85b7976 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -81,4 +81,13 @@ describe('mapCache', () => { expect(mapCache.size()).toBe(2) }) + + it('deletes cached values after expiration time when delete is true', async () => { + await mapCache.fetch({ key, callback, expiresInSeconds: 1, deleteOnExpiry: true }) + + expect(mapCache.size()).toBe(1) + await new Promise(resolve => setTimeout(resolve, 1050)); // wait a little longer than 1s + expect(mapCache.size()).toBe(0) + }) + })