缓存的纪念设施
目录
开始
要开始 @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。 。 。 .