@a-shui/lite-req-cache
v1.0.1
Published
A zero-dependency, LRU-based Promise caching library for Browser and Node.js
Maintainers
Readme
lite-req-cache 快速启动说明文档
一、环境准备
1.1 系统要求
- Node.js >= 14.0.0
- pnpm >= 8.x(推荐)或 npm / yarn
1.2 安装 Node.js
如果尚未安装 Node.js,请前往 Node.js 官网 下载并安装 LTS 版本。
验证安装:
node -v
npm -v1.3 安装 pnpm(推荐)
npm install -g pnpm
# 验证安装
pnpm -v二、项目启动步骤
2.1 克隆/下载项目
# 进入项目目录
cd lite-req-cache2.2 安装依赖
# 使用 pnpm(推荐)
pnpm install
# 或使用 npm
npm install
# 或使用 yarn
yarn install2.3 构建项目
pnpm build构建成功后会生成 dist/ 目录,包含:
index.mjs- ESM 格式index.cjs- CommonJS 格式index.d.ts- TypeScript 类型声明
2.4 运行测试
# 单次运行测试
pnpm test
# 监听模式(开发时使用)
pnpm test:watch三、使用示例
3.1 基础用法
import reqCache from 'lite-req-cache';
// 原始异步函数
const fetchData = async (name: string) => {
const response = await fetch(`/api/data?name=${name}`);
return response.json();
};
// 包装为缓存版本(缓存 3000ms)
const cachedFetchData = reqCache(fetchData, 3000);
// 使用
await cachedFetchData('test'); // 真实发起请求
await cachedFetchData('test'); // 命中缓存,不发起请求3.2 进阶用法
import reqCache from 'lite-req-cache';
const fetchUserList = reqCache(
async (params: { page: number; keyword: string; timestamp: number }) => {
// ...请求逻辑
},
{
ttl: 5000, // 缓存 5 秒
max: 20, // LRU 最大缓存 20 条
keyResolver: (params) => `${params.page}_${params.keyword}` // 自定义缓存键
}
);3.3 在不同环境中使用
ES Modules (ESM)
import reqCache from 'lite-req-cache';CommonJS (CJS)
const reqCache = require('lite-req-cache').default;
// 或
const { default: reqCache } = require('lite-req-cache');四、核心功能验证
4.1 验证缓存命中
let callCount = 0;
const fn = reqCache(async (x) => {
callCount++;
return x * 2;
}, 1000);
await fn(1); // callCount = 1
await fn(1); // callCount = 1 (命中缓存)
await fn(2); // callCount = 2 (不同参数)4.2 验证 TTL 过期
const fn = reqCache(async (x) => Date.now(), 100);
const t1 = await fn(1);
await new Promise(r => setTimeout(r, 200));
const t2 = await fn(1);
console.log(t1 !== t2); // true,缓存已过期重新请求4.3 验证失败不缓存
let failCount = 0;
const fn = reqCache(async () => {
failCount++;
if (failCount === 1) throw new Error('fail');
return 'success';
}, 5000);
try { await fn(); } catch (e) {} // 第一次失败
const result = await fn(); // 第二次重新请求,成功
console.log(result); // 'success'五、常见问题
Q1: 构建时提示找不到 tslib
解决方案:安装 tslib 开发依赖
pnpm add -D tslibQ2: 测试运行失败
解决方案:
- 确保依赖已完整安装:
pnpm install - 检查 Node.js 版本:
node -v(需要 >= 14)
Q3: 类型推断不正确
解决方案: 确保使用 TypeScript 4.x+ 版本,并在 tsconfig.json 中启用 strict 模式。
六、发布到 NPM(开发者)
# 1. 登录 npm
npm login
# 2. 发布
npm publish
# 3. 验证发布成功
npm info lite-req-cache七、技术支持
- 问题反馈:请提交 GitHub Issue
- 文档位置:
md/目录下的需求文档和架构文档
