Cache - support expiration dates

This commit is contained in:
Garrett Mills 2021-03-09 10:38:02 -06:00
parent 088fdfb1ef
commit be32976498
Signed by: garrettmills
GPG Key ID: D2BF5FBA8298F246
2 changed files with 17 additions and 6 deletions

View File

@ -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<void>;
public abstract put(key: string, value: string, expires?: Date): void | Promise<void>;
/**
* Check if the cache has the given key.

View File

@ -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<string | undefined> | 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<void> {
public put(key: string, value: string, expires?: Date): void | Promise<void> {
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<boolean> {
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<void> {