Skip to content

Commit

Permalink
refactor: deleting expired records
Browse files Browse the repository at this point in the history
  • Loading branch information
kukhariev committed Dec 11, 2024
1 parent 52a4fe4 commit 4c7d8b7
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions src/uploadx/lib/store.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const HOUR = 1000 * 60 * 60;

export class Store<T = string> {
private ttl = 24 * HOUR;
public ttl = 24 * HOUR;
constructor(readonly prefix = 'UPLOADX-v4.0-') {}

set(key: string, value: T): void {
Expand All @@ -12,8 +12,13 @@ export class Store<T = string> {
get(key: string): T | null {
const item = localStorage.getItem(this.prefix + key);
if (item) {
const [value, expires] = JSON.parse(item);
return value && expires ? value : null;
try {
const [value, expires] = JSON.parse(item) as [T, number];
if (Date.now() < expires) {
return value;
}
} catch {}
this.delete(key);
}
return null;
}
Expand All @@ -25,18 +30,20 @@ export class Store<T = string> {
clear(maxAgeHours = 0): void {
this.ttl = maxAgeHours * HOUR;
const now = Date.now();
this.keys().forEach(key => {
this._keys().forEach(key => {
const item = localStorage.getItem(key);
if (item && maxAgeHours) {
const [, expires] = JSON.parse(item);
now > Number(expires) && localStorage.removeItem(key);
} else {
localStorage.removeItem(key);
try {
const [, expires] = JSON.parse(item) as [T, number];
now > expires && localStorage.removeItem(key);
return;
} catch {}
}
localStorage.removeItem(key);
});
}

private keys(): string[] {
private _keys(): string[] {
return Object.keys(localStorage).filter(key => key.indexOf(this.prefix) === 0);
}
}
Expand Down

0 comments on commit 4c7d8b7

Please sign in to comment.