import { DateUtil } from '../utils'; import { CacheDriver } from './cache.symbols'; export class InMemoryDriver implements CacheDriver { private readonly cache: Record = {}; async get(key: string): Promise { const property = this.cache[key]; if (!property || !property.ttl?.isInTheFuture()) { return null; } return property.val; } set(key: string, val: string): Promise<'OK'> { this.cache[key] = { val }; return Promise.resolve('OK'); } exists(...keys: string[]): Promise { return Promise.resolve( keys.reduce((acc, k) => { if (k in this.cache) { return acc + 1; } return acc; }, 0) ); } async expire(key: string, seconds: number): Promise { const dateUtil = DateUtil.fromDate(new Date()).addNSeconds(seconds); const property = this.cache[key]; if (!property) { return 0; } property.ttl = dateUtil; return 1; } del(key: string): Promise { delete this.cache[key]; return Promise.resolve(1); } }