@ureq/lib-cache-store
v0.0.3
Published
Cache store implementations for universal request library
Readme
@ureq/lib-cache-store
缓存存储实现,提供内存缓存和 Storage 缓存。
安装
npm install @ureq/lib-cache-store
# 或
pnpm add @ureq/lib-cache-store使用
MemoryCacheStore
内存缓存实现,适用于浏览器和 Node.js。
import { Request } from '@ureq/core';
import { FetchRequestor } from '@ureq/impl-fetch';
import { MemoryCacheStore } from '@ureq/lib-cache-store';
const cacheStore = new MemoryCacheStore();
const request = new Request(
new FetchRequestor(),
{
cache: {
store: cacheStore,
ttl: 60000 // 60 秒
}
}
);StorageCacheStore
基于 Web Storage API 的缓存实现(localStorage/sessionStorage)。
import { StorageCacheStore } from '@ureq/lib-cache-store';
// 使用 localStorage
const localCache = new StorageCacheStore(localStorage);
// 使用 sessionStorage
const sessionCache = new StorageCacheStore(sessionStorage);
const request = new Request(
new FetchRequestor(),
{
cache: {
store: localCache,
ttl: 3600000 // 1 小时
}
}
);API
MemoryCacheStore
class MemoryCacheStore implements CacheStore {
get<T>(key: string): Promise<T | null>;
set<T>(key: string, value: T, ttl: number): Promise<void>;
delete(key: string): Promise<void>;
clear(): Promise<void>;
}StorageCacheStore
class StorageCacheStore implements CacheStore {
constructor(storage: Storage);
get<T>(key: string): Promise<T | null>;
set<T>(key: string, value: T, ttl: number): Promise<void>;
delete(key: string): Promise<void>;
clear(): Promise<void>;
}特性
MemoryCacheStore
- ✅ 快速访问
- ✅ 支持浏览器和 Node.js
- ✅ 自动过期清理
- ⚠️ 数据不持久化
StorageCacheStore
- ✅ 数据持久化
- ✅ 跨页面共享(localStorage)
- ✅ 自动过期清理
- ⚠️ 仅支持浏览器
- ⚠️ 存储空间有限(通常 5-10MB)
示例
基础用法
import { MemoryCacheStore } from '@ureq/lib-cache-store';
const cache = new MemoryCacheStore();
// 存储数据
await cache.set('key', { data: 'value' }, 60000);
// 获取数据
const data = await cache.get('key');
// 删除数据
await cache.delete('key');
// 清空缓存
await cache.clear();持久化缓存
import { StorageCacheStore } from '@ureq/lib-cache-store';
const cache = new StorageCacheStore(localStorage);
// 数据会保存到 localStorage
await cache.set('user', { id: 1, name: 'John' }, 3600000);
// 刷新页面后仍然可以获取
const user = await cache.get('user');自定义缓存实现
import { CacheStore } from '@ureq/core';
class RedisCacheStore implements CacheStore {
async get<T>(key: string): Promise<T | null> {
// 从 Redis 获取
}
async set<T>(key: string, value: T, ttl: number): Promise<void> {
// 存储到 Redis
}
async delete(key: string): Promise<void> {
// 从 Redis 删除
}
async clear(): Promise<void> {
// 清空 Redis
}
}文档
查看完整文档:https://sunny-117.github.io/ureq
License
MIT
