interface ILocalStorageData<T> {
data: T;
expiresAt: number | null;
}
export class LocalStorage {
private static instance: LocalStorage;
private readonly prefix: string;
private constructor(prefix: string) {
this.prefix = prefix;
}
static getInstance(prefix = ''): LocalStorage {
if (!LocalStorage.instance) {
LocalStorage.instance = new LocalStorage(prefix);
}
return LocalStorage.instance;
}
private getPrefixedKey(key: string): string {
return `${this.prefix}_${key}`;
}
set<T>(key: string, value: T, expiresAt?: Date): void {
const data: ILocalStorageData<T> = {
data: value,
expiresAt: expiresAt ? expiresAt.getTime() : null,
};
localStorage.setItem(this.getPrefixedKey(key), JSON.stringify(data));
}
get<T>(key: string): T | null {
const data: ILocalStorageData<T> | null = JSON.parse(localStorage.getItem(this.getPrefixedKey(key)) || 'null');
if (!data) {
return null;
}
if (data.expiresAt !== null && data.expiresAt < new Date().getTime()) {
this.remove(key);
return null;
}
return data.data;
}
remove(key: string): void {
localStorage.removeItem(this.getPrefixedKey(key));
}
clear(): void {
localStorage.clear();
}
}
const storage = new LocalStorage()
storage.set('key1', 'value1', 10000)
const value1 = storage.get('key1')
const value2 = storage.get('key2', 'defaultValue')
storage.remove('key1')
storage.clear()