You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/src/support/cache/MemoryCache.ts

44 lines
1.6 KiB

import {Collection} from "@extollo/util"
import {Cache} from "./Cache"
/**
* An in-memory implementation of the Cache.
* This is the default implementation for compatibility, but applications should switch to a persistent-backed cache driver.
*/
export class MemoryCache extends Cache {
/** Static collection of in-memory cache items. */
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
.where('key', '=', key)
.firstWhere(item => {
return !item.expires || now < item.expires
})?.value
}
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, expires })
}
}
public has(key: string): boolean | Promise<boolean> {
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> {
MemoryCache.cacheItems = MemoryCache.cacheItems.where('key', '!=', key)
}
}