Skip to content

Repository files navigation

LocalCache

一个基于 localStorage 的 TypeScript 缓存管理库,提供类型安全的缓存操作、自动过期清理和存储空间管理功能。

特性

  • 🚀 类型安全: 完整的 TypeScript 支持,提供类型推断和检查
  • ⏰ 过期管理: 支持设置缓存过期时间,自动清理过期数据
  • 🧹 自动清理: 初始化时自动清理过期缓存,保持存储空间整洁
  • 📦 存储管理: 内置存储空间限制和自动清理机制
  • 🛡️ 错误处理: 统一的错误处理机制,确保应用稳定性
  • 🔧 灵活配置: 支持自定义存储对象和大小限制

安装

npm install local-cache-ts
# 或
yarn add local-cache-ts
# 或
pnpm add local-cache-ts

快速开始

import cacheStorage from 'local-cache-ts';

// 设置缓存(永不过期)
cacheStorage.set('user', { id: 1, name: 'John Doe' });

// 设置带过期时间的缓存(1小时后过期)
cacheStorage.set('token', 'abc123', 60 * 60 * 1000);

// 获取缓存
const user = cacheStorage.get<{ id: number; name: string }>('user');
const token = cacheStorage.get<string>('token');

// 检查缓存是否存在
if (cacheStorage.has('user')) {
  console.log('用户缓存存在');
}

// 删除缓存
cacheStorage.remove('token');

// 清空所有缓存
cacheStorage.clear();

API 文档

构造函数

new CacheStorage(cache?: Storage, maxLocalStorageSize?: number)
  • cache: 存储对象,默认使用 localStorage
  • maxLocalStorageSize: 最大存储空间限制(字节),默认 5MB

方法

set<T>(key: string, value: T, expire?: number): void

设置缓存项。

  • key: 缓存键
  • value: 要缓存的值,支持任意可序列化的类型
  • expire: 过期时间(毫秒),0 表示永不过期,默认为 0
// 设置永不过期的缓存
cache.set('config', { theme: 'dark', lang: 'zh' });

// 设置1小时后过期的缓存
cache.set('session', 'session-id', 60 * 60 * 1000);

get<T>(key: string): T | null

获取缓存项。

  • key: 缓存键
  • 返回: 缓存的值,如果不存在、已过期或无效则返回 null
const config = cache.get<{ theme: string; lang: string }>('config');
if (config !== null) {
  console.log('主题:', config.theme);
}

has(key: string): boolean

检查缓存项是否存在且未过期。

if (cache.has('session')) {
  // 会话仍然有效
}

remove(key: string): void

删除指定缓存项。

cache.remove('session');

clear(): void

清空所有缓存。

cache.clear();

keys(): string[]

获取所有缓存键。

const allKeys = cache.keys();
console.log('所有缓存键:', allKeys);

getExpire(key: string): number

获取缓存项的过期时间戳。

const expireTime = cache.getExpire('session');
if (expireTime > 0) {
  console.log('过期时间:', new Date(expireTime));
}

setExpire(key: string, expire: number): void

设置缓存项的过期时间。

// 延长会话到2小时后过期
cache.setExpire('session', 2 * 60 * 60 * 1000);

// 设置为永不过期
cache.setExpire('config', 0);

deleteAllExpires(): void

删除所有过期缓存项。

// 手动清理过期缓存
cache.deleteAllExpires();

高级用法

使用 sessionStorage

import { CacheStorage } from 'local-cache-ts';

const sessionCache = new CacheStorage(sessionStorage);
sessionCache.set('tempData', { id: 1 }, 30 * 60 * 1000); // 30分钟后过期

自定义存储大小限制

import { CacheStorage } from 'local-cache-ts';

// 设置2MB的存储限制
const cache = new CacheStorage(localStorage, 2 * 1024 * 1024);

定期清理过期缓存

// 每小时清理一次过期缓存
setInterval(() => {
  cacheStorage.deleteAllExpires();
}, 60 * 60 * 1000);

类型安全的缓存操作

interface User {
  id: number;
  name: string;
  email: string;
}

interface Config {
  theme: 'light' | 'dark';
  language: string;
}

// 类型安全的设置和获取
cacheStorage.set<User>('currentUser', {
  id: 1,
  name: 'John Doe',
  email: 'john@example.com'
});

const user = cacheStorage.get<User>('currentUser');
if (user) {
  console.log(`用户: ${user.name} (${user.email})`);
}

错误处理

库内置了完善的错误处理机制:

  • 序列化错误: 当数据无法序列化时会抛出错误
  • 存储空间不足: 自动清理过期缓存后重试
  • 数据损坏: 自动清理无效的缓存项
  • JSON 解析错误: 优雅处理并清理损坏的数据
try {
  cacheStorage.set('data', someComplexObject);
} catch (error) {
  console.error('缓存设置失败:', error.message);
}

浏览器兼容性

  • Chrome 4+
  • Firefox 3.5+
  • Safari 4+
  • IE 8+
  • Edge (所有版本)

注意事项

  1. 存储限制: localStorage 通常有 5-10MB 的存储限制,具体取决于浏览器
  2. 同步操作: 所有操作都是同步的,大量数据操作可能影响性能
  3. 跨域限制: localStorage 受同源策略限制
  4. 隐私模式: 某些浏览器的隐私模式可能限制 localStorage 的使用

开发

# 克隆仓库
git clone https://github.com/your-username/localCache.git
cd localCache

# 安装依赖
npm install

# 构建
npm run build

# 运行测试
npm test

贡献

欢迎提交 Issue 和 Pull Request!

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 开启 Pull Request

许可证

MIT License - 查看 LICENSE 文件了解详情。

更新日志

v1.0.0

  • 初始版本发布
  • 支持基本的缓存操作
  • 支持过期时间管理
  • 支持自动清理功能
  • 完整的 TypeScript 支持

About

一个基于localStorage的TypeScript缓存管理库,支持过期时间、自动清理和类型安全

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages