Cache - support expiration dates

r0.1.5
Garrett Mills 3 years ago
parent 088fdfb1ef
commit be32976498
Signed by: garrettmills
GPG Key ID: D2BF5FBA8298F246

@ -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.

@ -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> {

Loading…
Cancel
Save