From 4c7d8b7e8c4449f599c59f88abb123f7aece81ee Mon Sep 17 00:00:00 2001 From: q_h Date: Wed, 11 Dec 2024 09:52:28 +0300 Subject: [PATCH] refactor: deleting expired records --- src/uploadx/lib/store.ts | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/uploadx/lib/store.ts b/src/uploadx/lib/store.ts index b5188da7..6d691512 100644 --- a/src/uploadx/lib/store.ts +++ b/src/uploadx/lib/store.ts @@ -1,7 +1,7 @@ const HOUR = 1000 * 60 * 60; export class Store { - private ttl = 24 * HOUR; + public ttl = 24 * HOUR; constructor(readonly prefix = 'UPLOADX-v4.0-') {} set(key: string, value: T): void { @@ -12,8 +12,13 @@ export class Store { 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; } @@ -25,18 +30,20 @@ export class Store { 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); } }