61 lines
1.1 KiB
TypeScript
61 lines
1.1 KiB
TypeScript
![]() |
import Timeout = NodeJS.Timeout;
|
||
|
|
||
|
const CLEAN_INTERVAL = 1000;
|
||
|
|
||
|
export class SimpleCache {
|
||
|
protected readonly retentionTime;
|
||
|
protected cleanTimeout: Timeout;
|
||
|
protected unloaded: boolean;
|
||
|
|
||
|
protected store: Map<string, { remove_at: number; value: any }>;
|
||
|
|
||
|
constructor(retentionTime) {
|
||
|
this.retentionTime = retentionTime;
|
||
|
this.store = new Map();
|
||
|
}
|
||
|
|
||
|
unload() {
|
||
|
this.unloaded = true;
|
||
|
clearTimeout(this.cleanTimeout);
|
||
|
}
|
||
|
|
||
|
cleanLoop() {
|
||
|
const now = Date.now();
|
||
|
for (const [key, info] of this.store.entries()) {
|
||
|
if (now >= info.remove_at) {
|
||
|
this.store.delete(key);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (!this.unloaded) {
|
||
|
this.cleanTimeout = setTimeout(() => this.cleanLoop(), CLEAN_INTERVAL);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
set(key: string, value) {
|
||
|
this.store.set(key, {
|
||
|
remove_at: Date.now() + this.retentionTime,
|
||
|
value,
|
||
|
});
|
||
|
}
|
||
|
|
||
|
get(key: string) {
|
||
|
const info = this.store.get(key);
|
||
|
if (!info) return null;
|
||
|
|
||
|
return info.value;
|
||
|
}
|
||
|
|
||
|
has(key: string) {
|
||
|
return this.store.has(key);
|
||
|
}
|
||
|
|
||
|
delete(key: string) {
|
||
|
this.store.delete(key);
|
||
|
}
|
||
|
|
||
|
clear() {
|
||
|
this.store.clear();
|
||
|
}
|
||
|
}
|