typescript 封装localStorage存取 带过期时间

173 阅读1分钟

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() 
// 存储一个值,过期时间为10秒 
storage.set('key1', 'value1', 10000)
// 获取一个值,如果不存在或者已经过期,则返回null 
const value1 = storage.get('key1') 
// 获取一个值,如果不存在或者已经过期,则返回默认值
const value2 = storage.get('key2', 'defaultValue')
// 删除一个值
storage.remove('key1')
// 清空所有的存储值 
storage.clear()