@via-cli/cache-tools
v0.0.2
Published
用于项目中的缓存
Readme
@via-cli/cache-tools
简洁易用的缓存管理工具包,支持多种存储方式和命名空间隔离。提供单例模式和构造函数模式两种使用方式。
✨ 特性
- 🚀 简单易用 - 只需要记住 5 个核心方法:
get、set、remove、has、clear - 🔧 自动适配 - 单例模式自动检测最佳存储方式,浏览器端优先使用localStorage
- 🏗️ 双模式 - 支持单例模式(开箱即用)和构造函数模式(自定义存储类型)
- 📦 命名空间 - 支持数据隔离,避免命名冲突
- ⏰ 过期控制 - 灵活的过期时间设置
- 🔒 加密存储 - 内置加密功能,保护敏感数据
- 📊 统计信息 - 提供缓存命中率等统计数据
- 💾 多存储 - 支持内存、localStorage、sessionStorage
📦 安装
pnpm add @via-cli/cache-tools
```e-tools
简洁易用的缓存管理工具包,支持多种存储方式和命名空间隔离,遵循最少知识原则设计。
## ✨ 特性
- **🚀 简单易用** - 只需要记住 5 个核心方法:`get`、`set`、`remove`、`has`、`clear`
- **🔧 自动适配** - 自动检测最佳存储方式,无需关心环境差异
- **� 命名空间** - 支持数据隔离,避免命名冲突
- **⏰ 过期控制** - 灵活的过期时间设置
- **🔒 加密存储** - 内置加密功能,保护敏感数据
- **� 统计信息** - 提供缓存命中率等统计数据
- **💾 多存储** - 支持内存、localStorage、sessionStorage
## � 安装
```bash
pnpm add @via-cli/cache-tools🚀 快速开始
基础用法
import { CacheTools } from '@via-cli/cache-tools'
// 设置缓存
CacheTools.set('userToken', 'abc123')
// 获取缓存
const token = CacheTools.get('userToken')
// 检查是否存在
if (CacheTools.has('userToken')) {
console.log('用户已登录')
}
// 删除缓存
CacheTools.remove('userToken')
// 清理所有缓存
CacheTools.clear()过期时间
// 设置5分钟过期
CacheTools.set('tempData', data, { expire: 300 })
// 设置1小时过期
CacheTools.set('userSession', session, { expire: 3600 })命名空间
// 用户相关数据
CacheTools.set('profile', userProfile, { namespace: 'user' })
CacheTools.set('settings', userSettings, { namespace: 'user' })
// 应用配置数据
CacheTools.set('theme', 'dark', { namespace: 'app' })
CacheTools.set('language', 'zh-CN', { namespace: 'app' })
// 获取命名空间数据
const profile = CacheTools.get('profile', { namespace: 'user' })
const theme = CacheTools.get('theme', { namespace: 'app' })
// 清理整个命名空间
CacheTools.clear({ namespace: 'user' })存储类型
// 自动检测(默认,推荐)
CacheTools.set('data', value)
// 使用内存存储(临时数据、高频读写)
CacheTools.set('cache', result, { storageType: 'memory' })
// 使用本地存储(持久化数据、跨会话保存)
CacheTools.set('config', settings, { storageType: 'localStorage' })
// 使用会话存储(会话级数据、标签页隔离)
CacheTools.set('tempSession', data, { storageType: 'sessionStorage' })加密存储
// 加密存储敏感数据
CacheTools.set('sensitiveData', 'secret', { encrypt: true })
// 解密获取
const secret = CacheTools.get('sensitiveData', { encrypt: true })
// 手动加密/解密
const encrypted = CacheTools.encrypt('sensitive data')
const decrypted = CacheTools.decrypt(encrypted)类型安全
interface UserProfile {
name: string
avatar: string
email: string
}
// 设置时自动推断类型
const profile: UserProfile = {
name: 'John Doe',
avatar: 'avatar.jpg',
email: '[email protected]'
}
CacheTools.set('profile', profile, { namespace: 'user' })
// 获取时指定类型
const userProfile = CacheTools.get<UserProfile>('profile', { namespace: 'user' })� 完整 API
CacheTools.set()
设置缓存项
CacheTools.set<T>(key: string, value: T, options?: CacheOptions): void参数:
key: 缓存键value: 缓存值options: 可选配置storageType: 存储类型 ('auto' | 'memory' | 'localStorage' | 'sessionStorage')namespace: 命名空间expire: 过期时间(秒)encrypt: 是否加密存储clearByLogout: 登出时是否清除
CacheTools.get()
获取缓存项
CacheTools.get<T>(key: string, options?: CacheOptions): T | undefined参数:
key: 缓存键options: 获取选项
返回: 缓存值或 undefined
CacheTools.has()
检查缓存项是否存在
CacheTools.has(key: string, options?: CacheOptions): booleanCacheTools.remove()
删除缓存项
CacheTools.remove(key: string, options?: CacheOptions): voidCacheTools.clear()
清理缓存
CacheTools.clear(options?: CacheOptions): void选项:
- 不传参数:清理当前存储类型的所有缓存
{ namespace: 'xxx' }: 清理指定命名空间{ storageType: 'localStorage' }: 清理指定存储类型
工具方法
// 获取统计信息
const stats = CacheTools.getStats()
console.log(`命中率: ${stats.hitRate}%`)
// 手动加密/解密
const encrypted = CacheTools.encrypt('data', 'optional-key')
const decrypted = CacheTools.decrypt(encrypted, 'optional-key')🏆 最佳实践
1. 存储类型选择
- 默认(推荐):使用
storageType: 'auto'或不指定,让工具自动选择 - 临时数据:使用
memory- 页面刷新后丢失 - 用户配置:使用
localStorage- 跨会话保持 - 会话数据:使用
sessionStorage- 标签页级别
2. 命名空间设计
// ✅ 推荐:按功能模块划分
CacheTools.set('token', token, { namespace: 'auth' })
CacheTools.set('profile', profile, { namespace: 'user' })
CacheTools.set('settings', settings, { namespace: 'app' })
// ❌ 避免:过深的层级
CacheTools.set('data', value, { namespace: 'app.user.profile.detail' })3. 过期时间设置
// 短期缓存(API 结果)
CacheTools.set('apiResult', data, { expire: 300 }) // 5分钟
// 会话级缓存(用户 token)
CacheTools.set('token', token, { expire: 3600 }) // 1小时
// 长期缓存(用户偏好)
CacheTools.set('preferences', prefs, { expire: 86400 }) // 1天
// 永久缓存(不设置 expire)
CacheTools.set('appConfig', config)4. 敏感数据处理
// ✅ 推荐:加密存储敏感数据
CacheTools.set('userCredentials', credentials, {
encrypt: true,
expire: 3600,
clearByLogout: true
})
// ❌ 避免:明文存储敏感信息
CacheTools.set('password', plainPassword) // 不安全🔧 环境兼容性
- 浏览器环境: 自动检测并优先使用 localStorage
- Node.js 环境: 自动使用内存存储
- 存储不可用: 自动降级到内存存储
🚦 注意事项
- 存储限制: localStorage/sessionStorage 有存储大小限制(通常 5-10MB)
- 序列化: 复杂对象会自动序列化,注意函数和循环引用会丢失
- 加密性能: 加密会增加存储和读取时间,谨慎在高频操作中使用
- 命名空间清理: 目前跨存储类型的命名空间清理可能不完全,建议明确指定存储类型
📄 License
MIT License
import { CacheManager } from '@via-cli/cache-tools'yarn add @via-cli/cache-tools
// 创建缓存实例
const cache = new CacheManager();## 🚀 快速开始
// 设置缓存### 基础缓存使用
cache.set('user', { name: 'John', age: 30 });
```typescript
// 获取缓存import { CacheManager } from '@via-cli/cache-tools';
const user = cache.get('user');
console.log(user); // { name: 'John', age: 30 }// 创建缓存实例
const cache = new CacheManager();
// 检查是否存在
if (cache.has('user')) {// 设置缓存(永不过期)
console.log('用户数据存在');cache.set('user', { name: 'John', age: 30 });
}
// 设置缓存(1小时后过期)
// 删除缓存cache.set('token', 'abc123', { expire: 3600 });
cache.remove('user');
// 获取缓存
// 清空所有缓存const user = cache.get('user');
cache.clear();const token = cache.get('token');
// 检查是否存在
2. 设置过期时间if (cache.has('user')) {
console.log('用户缓存存在');
// 设置5分钟后过期
cache.set('sessionData', userData, { expire: 300 }); // 300秒 = 5分钟// 删除缓存
cache.remove('token');
// 设置1小时后过期
cache.set('token', 'abc123', { expire: 3600 }); // 3600秒 = 1小时// 清空所有缓存
```cache.clear();
3. 选择存储适配器
账户缓存使用
import { CacheManager } from '@via-cli/cache-tools'```typescript
import { AccountCache } from '@via-cli/cache-tools';
// 使用内存存储(默认,页面刷新后数据丢失)
const memoryCache = new CacheManager('memory');const cache = new AccountCache();
// 使用localStorage(持久化存储)// 初始化账户
const localCache = new CacheManager('localStorage');cache.initAccount('user123');
// 使用sessionStorage(会话存储)// 设置账户相关数据
const sessionCache = new CacheManager('sessionStorage');cache.setAccountItem('preferences', {
``` theme: 'dark',
language: 'zh-CN'
### 4. 批量操作});
```typescript// 获取账户数据
// 批量设置const preferences = cache.getAccountItem('preferences');
const items = [
{ key: 'user1', value: { name: 'Alice' } },// 切换账户 - 数据自动隔离
{ key: 'user2', value: { name: 'Bob' } },cache.initAccount('user456');
{ key: 'user3', value: { name: 'Charlie' } }cache.setAccountItem('preferences', {
]; theme: 'light',
language: 'en-US'
const result = cache.setMany(items);});
console.log(`成功: ${result.success}, 失败: ${result.failed}`);```
// 批量获取### 命名空间缓存使用
const users = cache.getMany(['user1', 'user2', 'user4']);
console.log(users); // { user1: {...}, user2: {...} }```typescript
```import { NamespaceCache } from '@via-cli/cache-tools';
### 5. 命名空间缓存const cache = new NamespaceCache();
```typescript// 在不同命名空间设置数据
import { NamespaceCache } from '@via-cli/cache-tools'cache.setInNamespace('user', 'profile', { name: 'John' });
cache.setInNamespace('app', 'config', { version: '1.0.0' });
const cache = new NamespaceCache();
// 从指定命名空间获取数据
// 在不同命名空间中存储数据const profile = cache.getFromNamespace('user', 'profile');
cache.setInNamespace('user', 'profile', { name: 'John', email: '[email protected]' });const config = cache.getFromNamespace('app', 'config');
cache.setInNamespace('user', 'settings', { theme: 'dark', language: 'zh' });```
cache.setInNamespace('app', 'config', { version: '1.0.0' });
## 📖 API 文档
// 从命名空间获取数据
const profile = cache.getFromNamespace('user', 'profile');### CacheManager (基础缓存)
const config = cache.getFromNamespace('app', 'config');
#### 构造函数
// 获取命名空间中的所有键- `new CacheManager(adapterType?: 'memory' | 'localStorage' | 'sessionStorage')`
const userKeys = cache.getNamespaceKeys('user');
// ['profile', 'settings']#### 方法
- `set(key: string, value: any, options?: StorageOptions): void` - 设置缓存
// 清空指定命名空间- `get(key: string, options?: GetOptions): any` - 获取缓存
cache.clearNamespace('user');- `remove(key: string, options?: GetOptions): boolean` - 删除缓存
```- `has(key: string, options?: GetOptions): boolean` - 检查缓存是否存在
- `clear(): void` - 清空所有缓存
### 6. 统计信息- `keys(namespace?: string): string[]` - 获取所有键名
- `getStats(): CacheStats` - 获取统计信息
```typescript
// 获取缓存统计信息### AccountCache (账户缓存)
const stats = cache.getStats();
console.log(`缓存大小: ${stats.size}`);继承自 CacheManager,额外提供:
console.log(`命中次数: ${stats.hits}`);- `initAccount(accountKey: string): void` - 初始化账户
console.log(`未命中次数: ${stats.misses}`);- `setAccountItem(key: string, value: any, options?: StorageOptions): void` - 设置账户缓存
console.log(`命中率: ${stats.hitRate}%`);- `getAccountItem(key: string, options?: GetOptions): any` - 获取账户缓存
NamespaceCache (命名空间缓存)
API 参考
继承自 CacheManager,额外提供:
CacheManager (BaseCache)- setInNamespace(namespace: string, key: string, value: any, options?: StorageOptions): void - 在命名空间中设置缓存
getFromNamespace(namespace: string, key: string, options?: GetOptions): any- 从命名空间获取缓存
方法- clearNamespace(namespace: string): void - 清空命名空间
set(key: string, value: any, options?: StorageOptions): void### 类型定义设置缓存项
options.expire?: number- 过期时间(秒)```typescriptoptions.namespace?: string- 命名空间interface StorageOptions {
expire?: number; // 过期时间(秒)
get(key: string, options?: GetOptions): anyclearByLogout?: boolean; // 登出时清理获取缓存项 namespace?: string; // 命名空间
options.namespace?: string- 命名空间}
remove(key: string, options?: GetOptions): booleaninterface CacheStats {- 删除缓存项 hits: number; // 命中次数
misses: number; // 未命中次数
has(key: string, options?: GetOptions): booleansize: number; // 缓存项数量- 检查缓存项是否存在 hitRate: number; // 命中率
}
`clear(): void````
- 清空所有缓存
🤝 贡献
keys(namespace?: string): string[]- 获取所有键名欢迎提交 Pull Request 或 Issue!
setMany(items: Array<{key: string, value: any, options?: StorageOptions}>): BulkResult## 📄 许可证- 批量设置
MIT © 朝阳前端团队
getMany(keys: string[], options?: GetOptions): Record<string, any>- 批量获取
getStats(): CacheStats- 获取统计信息
NamespaceCache
继承自 BaseCache,额外提供:
setInNamespace(namespace: string, key: string, value: any, options?: StorageOptions): void- 在指定命名空间设置缓存
getFromNamespace(namespace: string, key: string, options?: GetOptions): any- 从指定命名空间获取缓存
getNamespaceKeys(namespace: string): string[]- 获取命名空间中的所有键
clearNamespace(namespace: string): void- 清空指定命名空间
类型定义
interface StorageOptions {
expire?: number; // 过期时间(秒)
clearByLogout?: boolean; // 登出时清除
namespace?: string; // 命名空间
}
interface CacheStats {
hits: number; // 命中次数
misses: number; // 未命中次数
size: number; // 缓存项数量
hitRate: number; // 命中率
}
interface BulkResult {
success: number; // 成功数量
failed: number; // 失败数量
errors: string[]; // 错误信息
}项目结构
src/
├── index.ts # 入口文件
├── core/ # 核心功能
│ ├── types.ts # 类型定义
│ └── cache.ts # 基础缓存类
├── utils/ # 工具函数
│ ├── adapters.ts # 存储适配器
│ └── helpers.ts # 辅助函数
└── plugins/ # 插件功能
└── namespace.ts # 命名空间缓存使用场景
用户会话管理
const cache = new CacheManager('localStorage');
// 保存用户登录信息
cache.set('userToken', token, { expire: 7200 }); // 2小时过期
cache.set('userProfile', profile);多租户数据隔离
const cache = new NamespaceCache('localStorage');
// 不同租户的数据互不干扰
cache.setInNamespace('tenant1', 'config', config1);
cache.setInNamespace('tenant2', 'config', config2);临时数据缓存
const cache = new CacheManager('memory');
// 缓存API请求结果
cache.set('apiData', result, { expire: 300 }); // 5分钟过期最佳实践
选择合适的存储类型
memory: 临时数据,性能最好localStorage: 需要持久化的数据sessionStorage: 会话期间的数据
合理设置过期时间
- 频繁变化的数据设置较短过期时间
- 相对稳定的数据可以设置较长过期时间
使用命名空间避免键冲突
- 不同模块使用不同命名空间
- 多租户场景使用租户ID作为命名空间
定期检查缓存统计
- 监控命中率优化缓存策略
- 根据缓存大小决定清理策略
注意事项
- localStorage 和 sessionStorage 在某些环境(如 Node.js)中可能不可用
- 存储的数据会经过 JSON 序列化,确保数据可序列化
- 大量数据存储可能影响性能,建议合理使用
- 浏览器对 localStorage 有存储限制(通常5-10MB)
兼容性
- 支持所有现代浏览器
- 支持 Node.js 环境(使用内存存储)
- 支持 TypeScript 4.0+
许可证
MIT License
