storage.ts 2.18 KB
/**
 * 本地存储工具类
 * 支持 localStorage 和 sessionStorage
 */

type StorageType = 'local' | 'session';

class Storage {
  /**
   * 获取存储项数量
   */
  get length(): number {
    return this.storage.length;
  }

  private storage: globalThis.Storage;

  constructor(type: StorageType = 'local') {
    this.storage = type === 'local' ? localStorage : sessionStorage;
  }

  /**
   * 清空所有存储项
   */
  clear(): void {
    try {
      this.storage.clear();
    } catch (error) {
      console.error('清空存储失败:', error);
    }
  }

  /**
   * 获取存储项
   */
  get<T = any>(key: string): null | T {
    try {
      const item = this.storage.getItem(key);
      return item ? JSON.parse(item) : null;
    } catch (error) {
      console.error('读取数据失败:', error);
      return null;
    }
  }

  /**
   * 获取带过期时间的存储项
   */
  getWithExpiry<T = any>(key: string): null | T {
    const item = this.get<{ expiry: number; value: T }>(key);

    if (!item) {
      return null;
    }

    const now = Date.now();

    // 检查是否过期
    if (now > item.expiry) {
      this.remove(key);
      return null;
    }

    return item.value;
  }

  /**
   * 检查是否存在某个 key
   */
  has(key: string): boolean {
    return this.storage.getItem(key) !== null;
  }

  /**
   * 获取所有 keys
   */
  keys(): string[] {
    return Object.keys(this.storage);
  }

  /**
   * 移除存储项
   */
  remove(key: string): void {
    try {
      this.storage.removeItem(key);
    } catch (error) {
      console.error('移除数据失败:', error);
    }
  }

  /**
   * 设置存储项
   */
  set(key: string, value: any): void {
    try {
      const serializedValue = JSON.stringify(value);
      this.storage.setItem(key, serializedValue);
    } catch {}
  }

  /**
   * 设置带过期时间的存储项
   */
  setWithExpiry(key: string, value: any, expiryInMs: number): void {
    const now = Date.now();
    const item = {
      value,
      expiry: now + expiryInMs,
    };
    this.set(key, item);
  }
}

// 导出实例
export const localCache = new Storage('local');
export const sessionCache = new Storage('session');

export default Storage;