Skip to content

存储工具 (Storage)

@pt/utils/modules/storage 提供了多种存储方案的工具函数,包括本地存储、会话存储、Cookie存储以及云存储解决方案。

存储方案概览

本模块提供以下存储解决方案:

📦 本地存储

  • Cookie Store - Cookie 存储封装,支持加密、域名配置

☁️ 云存储

  • AWS S3 - Amazon S3 云存储上传工具

快速开始

typescript
import { 
  createLocalStorage, 
  createSessionStorage,
  cookieStore 
} from '@pt/utils/modules/storage';

// 创建本地存储实例
const storage = createLocalStorage('app:');
storage.set('user', { name: 'John' });

// 使用 Cookie 存储
cookieStore.set('token', 'abc123', true); // 第三个参数表示加密

// 创建会话存储
const sessionStorage = createSessionStorage('temp:');
sessionStorage.set('step', 1);

主要特性

  • 类型安全:完整的 TypeScript 支持
  • 前缀管理:避免键名冲突
  • 过期控制:支持设置数据过期时间
  • 数据加密:敏感数据加密存储
  • 云存储集成:支持 AWS S3 等云存储服务

最佳实践

  1. 使用前缀隔离数据:为不同模块使用不同前缀
  2. 敏感数据加密:对敏感信息使用 cookieStore 的加密功能
  3. 设置合理过期时间:避免敏感数据长期存储
  4. 类型安全:使用 TypeScript 泛型确保类型安全
typescript
// 为不同模块创建独立的存储实例
const userStorage = createLocalStorage('user:');
const settingsStorage = createLocalStorage('settings:');
const cacheStorage = createSessionStorage('cache:');

// 使用加密存储敏感信息
cookieStore.set('authToken', token, true);

// 设置合理的过期时间
userStorage.set('session', sessionData, 2 * 60 * 60 * 1000); // 2小时

相关文档

Released under the MIT License.