diff --git a/src/support/cache/Cache.ts b/src/support/cache/Cache.ts index 809a78c..2b2c054 100644 --- a/src/support/cache/Cache.ts +++ b/src/support/cache/Cache.ts @@ -13,8 +13,9 @@ export abstract class Cache { * Store the given value in the cache by key. * @param {string} key * @param {string} value + * @param {Date} [expires] */ - public abstract put(key: string, value: string): void | Promise; + public abstract put(key: string, value: string, expires?: Date): void | Promise; /** * Check if the cache has the given key. diff --git a/src/support/cache/MemoryCache.ts b/src/support/cache/MemoryCache.ts index 2c5f878..f175810 100644 --- a/src/support/cache/MemoryCache.ts +++ b/src/support/cache/MemoryCache.ts @@ -2,24 +2,34 @@ import {Collection} from "@extollo/util" import {Cache} from "./Cache" export class MemoryCache extends Cache { - private static cacheItems: Collection<{key: string, value: string}> = new Collection<{key: string; value: string}>() + private static cacheItems: Collection<{key: string, value: string, expires?: Date}> = new Collection<{key: string; value: string, expires?: Date}>() public fetch(key: string): string | Promise | undefined { + const now = new Date() return MemoryCache.cacheItems - .firstWhere('key', '=', key)?.value + .where('key', '=', key) + .firstWhere(item => { + return !item.expires || now < item.expires + })?.value } - public put(key: string, value: string): void | Promise { + public put(key: string, value: string, expires?: Date): void | Promise { const existing = MemoryCache.cacheItems.firstWhere('key', '=', key) if ( existing ) { existing.value = value + existing.expires = expires } else { - MemoryCache.cacheItems.push({ key, value }) + MemoryCache.cacheItems.push({ key, value, expires }) } } public has(key: string): boolean | Promise { - return !!MemoryCache.cacheItems.firstWhere('key', '=', key) + const now = new Date() + return !!MemoryCache.cacheItems + .where('key', '=', key) + .firstWhere(item => { + return !item.expires || now < item.expires + }) } public drop(key: string): void | Promise {