mirror of
https://github.com/ZeppelinBot/Zeppelin.git
synced 2025-03-16 14:11:50 +00:00
SimpleCache: allow specifying max items, add better type support
This commit is contained in:
parent
a0a30add2b
commit
6ff8c8d290
1 changed files with 15 additions and 6 deletions
|
@ -2,15 +2,19 @@ import Timeout = NodeJS.Timeout;
|
||||||
|
|
||||||
const CLEAN_INTERVAL = 1000;
|
const CLEAN_INTERVAL = 1000;
|
||||||
|
|
||||||
export class SimpleCache {
|
export class SimpleCache<T = any> {
|
||||||
protected readonly retentionTime;
|
protected readonly retentionTime: number;
|
||||||
|
protected readonly maxItems: number;
|
||||||
|
|
||||||
protected cleanTimeout: Timeout;
|
protected cleanTimeout: Timeout;
|
||||||
protected unloaded: boolean;
|
protected unloaded: boolean;
|
||||||
|
|
||||||
protected store: Map<string, { remove_at: number; value: any }>;
|
protected store: Map<string, { remove_at: number; value: T }>;
|
||||||
|
|
||||||
constructor(retentionTime) {
|
constructor(retentionTime: number, maxItems?: number) {
|
||||||
this.retentionTime = retentionTime;
|
this.retentionTime = retentionTime;
|
||||||
|
this.maxItems = maxItems;
|
||||||
|
|
||||||
this.store = new Map();
|
this.store = new Map();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -32,14 +36,19 @@ export class SimpleCache {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
set(key: string, value) {
|
set(key: string, value: T) {
|
||||||
this.store.set(key, {
|
this.store.set(key, {
|
||||||
remove_at: Date.now() + this.retentionTime,
|
remove_at: Date.now() + this.retentionTime,
|
||||||
value,
|
value,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (this.maxItems && this.store.size > this.maxItems) {
|
||||||
|
const keyToDelete = this.store.keys().next().value;
|
||||||
|
this.store.delete(keyToDelete);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
get(key: string) {
|
get(key: string): T {
|
||||||
const info = this.store.get(key);
|
const info = this.store.get(key);
|
||||||
if (!info) return null;
|
if (!info) return null;
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue