From d6c2ed5add59ed1f3acbf21651fdf3536c52f846 Mon Sep 17 00:00:00 2001 From: nekocode Date: Thu, 1 Dec 2022 20:42:46 +0800 Subject: [PATCH] fix(memory): passing 0 to ttl argument does not work (#282) --- src/stores/memory.ts | 6 +++--- test/stores/memory.test.ts | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/stores/memory.ts b/src/stores/memory.ts index 786392ed..23a75b99 100644 --- a/src/stores/memory.ts +++ b/src/stores/memory.ts @@ -36,7 +36,7 @@ export function memoryStore(args?: MemoryConfig): MemoryStore { const lruOpts = { ...args, max: args?.max || 500, - ttl: args?.ttl ? args.ttl : 0, + ttl: args?.ttl !== undefined ? args.ttl : 0, }; const lruCache = new LRUCache(lruOpts); @@ -49,7 +49,7 @@ export function memoryStore(args?: MemoryConfig): MemoryStore { keys: async () => [...lruCache.keys()], mget: async (...args) => args.map((x) => lruCache.get(x)), async mset(args, ttl?) { - const opt = { ttl: ttl ? ttl : lruOpts.ttl } as const; + const opt = { ttl: ttl !== undefined ? ttl : lruOpts.ttl } as const; for (const [key, value] of args) { if (!isCacheable(value)) throw new Error(`no cacheable value ${JSON.stringify(value)}`); @@ -69,7 +69,7 @@ export function memoryStore(args?: MemoryConfig): MemoryStore { throw new Error(`no cacheable value ${JSON.stringify(value)}`); if (shouldCloneBeforeSet) value = clone(value); - const ttl = opt ? opt : lruOpts.ttl; + const ttl = opt !== undefined ? opt : lruOpts.ttl; lruCache.set(key, value, { ttl }); }, diff --git a/test/stores/memory.test.ts b/test/stores/memory.test.ts index 6ddf0466..df97cde3 100644 --- a/test/stores/memory.test.ts +++ b/test/stores/memory.test.ts @@ -24,6 +24,13 @@ describe('memory store', () => { await expect(store.get('foo')).resolves.toEqual('bar'); }); + it('when ttl arg is passed 0', async () => { + const store = memoryStore({ ttl: 1 }); + await store.set('foo', 'bar', 0); + await sleep(20); + await expect(store.get('foo')).resolves.toEqual('bar'); + }); + it('cache record should be expired', async () => { await store.set('foo', 'bar', 1); await sleep(20);