homelab-personal-cloud/core/src/cache/in-memory.driver.ts

51 lines
1.1 KiB
TypeScript

import { DateUtil } from '../utils';
import { CacheDriver } from './cache.symbols';
export class InMemoryDriver implements CacheDriver {
private readonly cache: Record<string, { val: string, ttl?: DateUtil }> = {};
async get(key: string): Promise<string | null> {
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<number> {
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<number> {
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<number> {
delete this.cache[key];
return Promise.resolve(1);
}
}