@cacheable/utils 2.0.3 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +138 -2
- package/dist/index.cjs +637 -1
- package/dist/index.d.cts +54 -1
- package/dist/index.d.ts +54 -1
- package/dist/index.js +582 -1
- package/package.json +11 -10
package/README.md
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* Coalesce Async for Handling Multiple Promises
|
|
16
16
|
* Stats Helpers for Caching Statistics
|
|
17
17
|
* Sleep / Delay for Testing and Timing
|
|
18
|
+
* Memoization for wraping or get / set options
|
|
18
19
|
* Time to Live (TTL) Helpers
|
|
19
20
|
|
|
20
21
|
# Table of Contents
|
|
@@ -29,13 +30,13 @@
|
|
|
29
30
|
* [Run if Function Helper](#run-if-function-helper)
|
|
30
31
|
* [Less Than Helper](#less-than-helper)
|
|
31
32
|
* [Is Object Helper](#is-object-helper)
|
|
33
|
+
* [Wrap / Memoization for Sync and Async Functions](#wrap--memoization-for-sync-and-async-functions)
|
|
34
|
+
* [Get Or Set Memoization Function](#get-or-set-memoization-function)
|
|
32
35
|
* [How to Contribute](#how-to-contribute)
|
|
33
36
|
* [License and Copyright](#license-and-copyright)
|
|
34
37
|
|
|
35
38
|
# Getting Started
|
|
36
39
|
|
|
37
|
-
`cacheable` is primarily used as an extension to your caching engine with a robust storage backend [Keyv](https://keyv.org), Memoization (Wrap), Hooks, Events, and Statistics.
|
|
38
|
-
|
|
39
40
|
```bash
|
|
40
41
|
npm install @cacheable/utils --save
|
|
41
42
|
```
|
|
@@ -335,6 +336,141 @@ This utility is particularly useful for:
|
|
|
335
336
|
- **Configuration parsing** - Validating that configuration values are objects
|
|
336
337
|
- **Data filtering** - Separating objects from other data types
|
|
337
338
|
|
|
339
|
+
# Wrap / Memoization for Sync and Async Functions
|
|
340
|
+
|
|
341
|
+
The `@cacheable/utils` package provides two main functions: `wrap` and `wrapSync`. These functions are used to memoize asynchronous and synchronous functions, respectively.
|
|
342
|
+
|
|
343
|
+
```javascript
|
|
344
|
+
import { Cacheable } from 'cacheable';
|
|
345
|
+
const asyncFunction = async (value: number) => {
|
|
346
|
+
return Math.random() * value;
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
const cache = new Cacheable();
|
|
350
|
+
const options = {
|
|
351
|
+
ttl: '1h', // 1 hour
|
|
352
|
+
keyPrefix: 'p1', // key prefix. This is used if you have multiple functions and need to set a unique prefix.
|
|
353
|
+
cache,
|
|
354
|
+
}
|
|
355
|
+
const wrappedFunction = wrap(asyncFunction, options);
|
|
356
|
+
console.log(await wrappedFunction(2)); // 4
|
|
357
|
+
console.log(await wrappedFunction(2)); // 4 from cache
|
|
358
|
+
```
|
|
359
|
+
With `wrap` we have also included stampede protection so that a `Promise` based call will only be called once if multiple requests of the same are executed at the same time. Here is an example of how to test for stampede protection:
|
|
360
|
+
|
|
361
|
+
```javascript
|
|
362
|
+
import { Cacheable } from 'cacheable';
|
|
363
|
+
const asyncFunction = async (value: number) => {
|
|
364
|
+
return value;
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
const cache = new Cacheable();
|
|
368
|
+
const options = {
|
|
369
|
+
ttl: '1h', // 1 hour
|
|
370
|
+
keyPrefix: 'p1', // key prefix. This is used if you have multiple functions and need to set a unique prefix.
|
|
371
|
+
cache,
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const wrappedFunction = wrap(asyncFunction, options);
|
|
375
|
+
const promises = [];
|
|
376
|
+
for (let i = 0; i < 10; i++) {
|
|
377
|
+
promises.push(wrappedFunction(i));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const results = await Promise.all(promises); // all results should be the same
|
|
381
|
+
|
|
382
|
+
console.log(results); // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
In this example we are wrapping an `async` function in a cache with a `ttl` of `1 hour`. This will cache the result of the function for `1 hour` and then expire the value. You can also wrap a `sync` function in a cache:
|
|
386
|
+
|
|
387
|
+
```javascript
|
|
388
|
+
import { CacheableMemory } from 'cacheable';
|
|
389
|
+
const syncFunction = (value: number) => {
|
|
390
|
+
return value * 2;
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
const cache = new CacheableMemory();
|
|
394
|
+
const wrappedFunction = wrap(syncFunction, { ttl: '1h', key: 'syncFunction', cache });
|
|
395
|
+
console.log(wrappedFunction(2)); // 4
|
|
396
|
+
console.log(wrappedFunction(2)); // 4 from cache
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
In this example we are wrapping a `sync` function in a cache with a `ttl` of `1 hour`. This will cache the result of the function for `1 hour` and then expire the value. You can also set the `key` property in the `wrap()` options to set a custom key for the cache.
|
|
400
|
+
|
|
401
|
+
When an error occurs in the function it will not cache the value and will return the error. This is useful if you want to cache the results of a function but not cache the error. If you want it to cache the error you can set the `cacheError` property to `true` in the `wrap()` options. This is disabled by default.
|
|
402
|
+
|
|
403
|
+
```javascript
|
|
404
|
+
import { CacheableMemory } from 'cacheable';
|
|
405
|
+
const syncFunction = (value: number) => {
|
|
406
|
+
throw new Error('error');
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
const cache = new CacheableMemory();
|
|
410
|
+
const wrappedFunction = wrap(syncFunction, { ttl: '1h', key: 'syncFunction', cacheError: true, cache });
|
|
411
|
+
console.log(wrappedFunction()); // error
|
|
412
|
+
console.log(wrappedFunction()); // error from cache
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
If you would like to generate your own key for the wrapped function you can set the `createKey` property in the `wrap()` options. This is useful if you want to generate a key based on the arguments of the function or any other criteria.
|
|
416
|
+
|
|
417
|
+
```javascript
|
|
418
|
+
const cache = new Cacheable();
|
|
419
|
+
const options: WrapOptions = {
|
|
420
|
+
cache,
|
|
421
|
+
keyPrefix: 'test',
|
|
422
|
+
createKey: (function_, arguments_, options: WrapOptions) => `customKey:${options?.keyPrefix}:${arguments_[0]}`,
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
const wrapped = wrap((argument: string) => `Result for ${argument}`, options);
|
|
426
|
+
|
|
427
|
+
const result1 = await wrapped('arg1');
|
|
428
|
+
const result2 = await wrapped('arg1'); // Should hit the cache
|
|
429
|
+
|
|
430
|
+
console.log(result1); // Result for arg1
|
|
431
|
+
console.log(result2); // Result for arg1 (from cache)
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
We will pass in the `function` that is being wrapped, the `arguments` passed to the function, and the `options` used to wrap the function. You can then use these to generate a custom key for the cache.
|
|
435
|
+
|
|
436
|
+
# Get Or Set Memoization Function
|
|
437
|
+
|
|
438
|
+
The `getOrSet` method provides a convenient way to implement the cache-aside pattern. It attempts to retrieve a value from cache, and if not found, calls the provided function to compute the value and store it in cache before returning it. Here are the options:
|
|
439
|
+
|
|
440
|
+
```typescript
|
|
441
|
+
export type GetOrSetFunctionOptions = {
|
|
442
|
+
ttl?: number | string;
|
|
443
|
+
cacheErrors?: boolean;
|
|
444
|
+
throwErrors?: boolean;
|
|
445
|
+
};
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
Here is an example of how to use the `getOrSet` method:
|
|
449
|
+
|
|
450
|
+
```javascript
|
|
451
|
+
import { Cacheable } from 'cacheable';
|
|
452
|
+
const cache = new Cacheable();
|
|
453
|
+
// Use getOrSet to fetch user data
|
|
454
|
+
const function_ = async () => Math.random() * 100;
|
|
455
|
+
const value = await getOrSet('randomValue', function_, { ttl: '1h', cache });
|
|
456
|
+
console.log(value); // e.g. 42.123456789
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
You can also use a function to compute the key for the function:
|
|
460
|
+
|
|
461
|
+
```javascript
|
|
462
|
+
import { Cacheable, GetOrSetOptions } from 'cacheable';
|
|
463
|
+
const cache = new Cacheable();
|
|
464
|
+
|
|
465
|
+
// Function to generate a key based on options
|
|
466
|
+
const generateKey = (options?: GetOrSetOptions) => {
|
|
467
|
+
return `custom_key_:${options?.cacheId || 'default'}`;
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
const function_ = async () => Math.random() * 100;
|
|
471
|
+
const value = await getOrSet(generateKey(), function_, { ttl: '1h', cache });
|
|
472
|
+
```
|
|
473
|
+
|
|
338
474
|
# How to Contribute
|
|
339
475
|
|
|
340
476
|
You can contribute by forking the repo and submitting a pull request. Please make sure to add tests and update the documentation. To learn more about how to contribute go to our main README [https://github.com/jaredwray/cacheable](https://github.com/jaredwray/cacheable). This will talk about how to `Open a Pull Request`, `Ask a Question`, or `Post an Issue`.
|