扫一扫分享
「cacheables」正如它名字一样,是用来做内存缓存使用,其代码仅仅 200 行左右(不含注释),一个简单的内存缓存,支持不同的缓存策略,使用 TypeScript 编写优雅的语法。
当我们业务中需要对请求等异步任务做缓存,避免重复请求时,完全可以使用上「cacheables」。上手 cacheables很简单,看看下面使用对比:
// 没有使用缓存
fetch("https://some-url.com/api");
// 有使用缓存
cache.cacheable(() => fetch("https://some-url.com/api"), "key");
接下来看下官网提供的缓存请求的使用示例:
npm install cacheables
// 或者
pnpm add cacheables
import { Cacheables } from "cacheables";
const apiUrl = "http://localhost:3000/";
// 创建一个新的缓存实例 ①
const cache = new Cacheables({
logTiming: true,
log: true,
});
// 模拟异步任务
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
// 包装一个现有 API 调用 fetch(apiUrl),并分配一个 key 为 weather
// 下面例子使用 'max-age' 缓存策略,它会在一段时间后缓存失效
// 该方法返回一个完整 Promise,就像' fetch(apiUrl) '一样,可以缓存结果。
const getWeatherData = () =>
// ②
cache.cacheable(() => fetch(apiUrl), "weather", {
cachePolicy: "max-age",
maxAge: 5000,
});
const start = async () => {
// 获取新数据,并添加到缓存中
const weatherData = await getWeatherData();
// 3秒之后再执行
await wait(3000);
// 缓存新数据,maxAge设置5秒,此时还未过期
const cachedWeatherData = await getWeatherData();
// 3秒之后再执行
await wait(3000);
// 缓存超过5秒,此时已过期,此时请求的数据将会再缓存起来
const freshWeatherData = await getWeatherData();
};
start();
上面示例代码我们就实现一个请求缓存的业务,在 maxAge为 5 秒内的重复请求,不会重新发送请求,而是从缓存读取其结果进行返回。
官方文档中介绍了很多 API,具体可以从文档中获取,比较常用的如 cache.cacheable(),用来包装一个方法进行缓存。
所有 API 如下:
手机预览