Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export interface FetchParams {
params?: any
callback(): any
expiresInSeconds?: number
deleteOnExpiry?: boolean
}

export interface KeyParams {
Expand Down Expand Up @@ -34,13 +35,14 @@ class MapCache implements IStorageCache {
key,
params = null,
callback,
expiresInSeconds = DEFAULT_EXPIRATION_SECONDS
expiresInSeconds = DEFAULT_EXPIRATION_SECONDS,
deleteOnExpiry = false
}: FetchParams): Promise<T> {
const cacheKey = this.generateKey({ key, params })
const data = this.get<T>(cacheKey)
const expiration = this.computeExpirationTime(expiresInSeconds)

return data ? data : this.set<T>({ key: cacheKey, data: await callback(), expiration })
return data ? data : this.set<T>({ key: cacheKey, data: await callback(), expiration}, deleteOnExpiry, expiresInSeconds)
}

clear(): void {
Expand Down Expand Up @@ -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<T>({ key, data, expiration }: StoredData<T>): T {
private set<T>({ key, data, expiration }: StoredData<T>, 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
}

Expand All @@ -87,7 +98,7 @@ class MapCache implements IStorageCache {
private get<T>(key: string): T | null {
if (this.cache.has(key)) {
const { data, expiration } = this.cache.get(key) as StoredData<T>

return this.hasExpired(expiration) ? null : data
}

Expand Down
9 changes: 9 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<IData>({ 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)
})

})