@cacheable/memoize

中文文档
2.0.3发布于 2025/10/02MITTypeScriptESM + CJS近 30 天下载 96.3万

可缓存的纪念工具

中文使用文档

Cacheable

缓存的纪念设施

codecov tests npm npm license

目录

开始

要开始 @cacheable/memoize,安装软件包 :

npm install @cacheable/memoize

同步和同步函数的环绕/备忘录

这个 @cacheable/memoize 软件包提供两个主要功能: wrap 财务报告和审定财务报表 wrapSync。这些函数分别用于记忆同步和同步函数.

import { Cacheable } from 'cacheable';
const asyncFunction = async (value: number) => {
  return Math.random() * value;
};

const cache = new Cacheable();
const options = {
  ttl: '1h', // 1 hour
  keyPrefix: 'p1', // key prefix. This is used if you have multiple functions and need to set a unique prefix.
  cache,
}
const wrappedFunction = wrap(asyncFunction, options);
console.log(await wrappedFunction(2)); // 4
console.log(await wrappedFunction(2)); // 4 from cache

与 wrap 我们还包括了盖章保护,以便 Promise 只有当同一请求的多个请求同时执行时,才会调用一次。 以下是如何测试保护邮票的例子:

import { Cacheable } from 'cacheable';
const asyncFunction = async (value: number) => {
  return value;
};

const cache = new Cacheable();
const options = {
  ttl: '1h', // 1 hour
  keyPrefix: 'p1', // key prefix. This is used if you have multiple functions and need to set a unique prefix.
  cache,
}

const wrappedFunction = wrap(asyncFunction, options);
const promises = [];
for (let i = 0; i < 10; i++) {
  promises.push(wrappedFunction(i));
}

const results = await Promise.all(promises); // all results should be the same

console.log(results); // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

在这个例子中,我们正在包装一个 async 函数在缓存中设置 ttl 联 合 国 1 hour。这将缓存函数的结果 1 hour ,然后过期值。 也可以包起来 sync 缓存中的函数 :

import { CacheableMemory } from 'cacheable';
const syncFunction = (value: number) => {
  return value * 2;
};

const cache = new CacheableMemory();
const wrappedFunction = wrap(syncFunction, { ttl: '1h', key: 'syncFunction', cache });
console.log(wrappedFunction(2)); // 4
console.log(wrappedFunction(2)); // 4 from cache

在这个例子中,我们正在包装一个 sync 函数在缓存中设置 ttl 联 合 国 1 hour。这将缓存函数的结果 1 hour ,然后过期值。 您也可以设置 key 属性 wrap() 选项为缓存设置自定义密钥.

当函数发生错误时,它不会缓存该值并返回错误。 如果您想要缓存函数的结果, 但不缓存出错, 此操作是有用的 。 如果您想要缓存错误, 您可以设置 cacheError 属性改为 true 输入 wrap() 选项。 此默认已禁用 .

import { CacheableMemory } from 'cacheable';
const syncFunction = (value: number) => {
  throw new Error('error');
};

const cache = new CacheableMemory();
const wrappedFunction = wrap(syncFunction, { ttl: '1h', key: 'syncFunction', cacheError: true, cache });
console.log(wrappedFunction()); // error
console.log(wrappedFunction()); // error from cache

如果您想要为包裹的函数生成自己的密钥, 您可以设置 createKey 属性 wrap() 选项。 如果您想要根据函数的参数或任何其他标准生成密钥,此选项是有用的 .

  const cache = new Cacheable();
  const options: WrapOptions = {
    cache,
    keyPrefix: 'test',
    createKey: (function_, arguments_, options: WrapOptions) => `customKey:${options?.keyPrefix}:${arguments_[0]}`,
  };

  const wrapped = wrap((argument: string) => `Result for ${argument}`, options);

  const result1 = await wrapped('arg1');
  const result2 = await wrapped('arg1'); // Should hit the cache

  console.log(result1); // Result for arg1
  console.log(result2); // Result for arg1 (from cache)

我们会通过在 function 被包裹着的 arguments 转到函数,和 options 用于包围函数。 然后可以使用这些来生成缓存的自定义密钥 .

获取或设置记忆函数

这个 getOrSet 方法提供了一种执行缓存-侧式的方便方式。 它试图从缓存中取出一个值,如果没有找到,它会调用提供的函数来计算该值,并存储在缓存中再返回. 以下是选项:

export type GetOrSetFunctionOptions = {
    ttl?: number | string;
    cacheErrors?: boolean;
    throwErrors?: boolean;
};

这里有一个例子 如何使用 getOrSet 方法 :

import { Cacheable } from 'cacheable';
const cache = new Cacheable();
// Use getOrSet to fetch user data
const function_ = async () => Math.random() * 100;
const value = await getOrSet('randomValue', function_, { ttl: '1h', cache });
console.log(value); // e.g. 42.123456789

您也可以使用函数来计算函数的密钥 :

import { Cacheable, GetOrSetOptions } from 'cacheable';
const cache = new Cacheable();

// Function to generate a key based on options
const generateKey = (options?: GetOrSetOptions) => {
  return `custom_key_:${options?.cacheId || 'default'}`;
};

const function_ = async () => Math.random() * 100;
const value = await getOrSet(generateKey(), function_, { ttl: '1h', cache });

如何贡献

你可以通过取消回购和提交拉力请求来贡献. 请确保添加测试并更新文档. 了解更多如何为我们的主要研究做出贡献 https://github.com/jaredwray/可切换这将谈论如何 Open a Pull Request, (中文(简体) ), Ask a Question,或 Post an Issue。 。 。 .

许可证和版权

麻省理工学院

版本与发布记录

@cacheable/memoize 共发布 7 个版本,首次发布于 2025/07/26;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.0.3latest2025/10/021.1 年前
2.0.22025/09/221.1 年前
2.0.12025/09/171.1 年前
2.0.02025/09/101.2 年前
1.1.12025/08/271.2 年前
1.1.02025/07/311.3 年前

关于 @cacheable/memoize 的常见问题

@cacheable/memoize 是什么?

可缓存的纪念工具

如何安装 @cacheable/memoize?

在项目目录运行 npm install @cacheable/memoize,或使用 pnpm add / yarn add / bun add。

@cacheable/memoize 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cacheable/memoize 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cacheable/memoize 可以商用吗?

@cacheable/memoize 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cacheable/memoize 的下载量有多少?

根据 npm 官方下载统计,@cacheable/memoize 在 2026/10/09 – 2026/11/07 这 30 天内被下载 962,731 次,日均约 32,091 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cacheable/memoize 还在维护吗?

最新版本 2.0.3 发布于 2025/10/02(1.1 年前);至今共发布 7 个版本,其中过去 12 个月发布了 0 个;首次发布于 2025/07/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。