99行 TypeScript 代码实现一个高效缓存库

325 阅读2分钟

它的特点:

  • 优雅的语法,包装现有 API 调用,节省 API 调用;
  • 完全输入的结果。不需要类型转换。
  • 支持不同的缓存策略。
  • 集成日志:检查 API 调用的时间。
  • 使用辅助函数来构建缓存 key。
  • 适用于浏览器和 Node.js。
  • 没有依赖。
  • 进行大范围测试。
  • 体积小,gzip 之后 1.43kb。

当我们业务中需要对请求等异步任务做缓存,避免重复请求时,完全可以使用上「cacheables」。

二、上手体验

上手 cacheables很简单,看看下面使用对比:

// 没有使用缓存
fetch("https://some-url.com/api");

// 有使用缓存
cache.cacheable(() => fetch("https://some-url.com/api"), "key");
复制代码

接下来看下官网提供的缓存请求的使用示例:

1. 安装依赖

npm install cacheables
// 或者
pnpm add cacheables
复制代码

2. 使用示例

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 秒内的重复请求,不会重新发送请求,而是从缓存读取其结果进行返回。

3. API 介绍

官方文档中介绍了很多 API,具体可以从文档中获取,比较常用的如 cache.cacheable(),用来包装一个方法进行缓存。 所有 API 如下:

  • new Cacheables(options?): Cacheables
  • cache.cacheable(resource, key, options?): Promise<T>
  • cache.delete(key: string): void
  • cache.clear(): void
  • cache.keys(): string[]
  • cache.isCached(key: string): boolean
  • Cacheables.key(...args: (string | number)[]): string