@cacheable/utils 2.1.0 → 2.3.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 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
  ```
@@ -99,25 +100,63 @@ console.log(result); // Data for my-key only executed once
99
100
 
100
101
  The `@cacheable/utils` package provides hash functions that can be used to generate unique keys for caching operations. These functions are useful for creating consistent and unique identifiers for cached items.
101
102
 
103
+ The hashing API provides both **async** (for cryptographic algorithms) and **sync** (for non-cryptographic algorithms) methods.
104
+
105
+ ## Async Hashing (Cryptographic Algorithms)
106
+
107
+ Use `hash()` and `hashToNumber()` for cryptographic algorithms like SHA-256, SHA-384, and SHA-512:
108
+
102
109
  ```typescript
103
- import { hash } from '@cacheable/utils';
110
+ import { hash, hashToNumber, HashAlgorithm } from '@cacheable/utils';
104
111
 
105
- const key = hash('my-cache-key');
112
+ // Hash using SHA-256 (default)
113
+ const key = await hash('my-cache-key');
106
114
  console.log(key); // Unique hash for 'my-cache-key'
115
+
116
+ // Hash with specific algorithm
117
+ const sha512Hash = await hash('my-data', { algorithm: HashAlgorithm.SHA512 });
118
+
119
+ // Convert hash to number within range
120
+ const min = 0;
121
+ const max = 10;
122
+ const result = await hashToNumber({foo: 'bar'}, { min, max, algorithm: HashAlgorithm.SHA256 });
123
+ console.log(result); // A number between 0 and 10 based on the hash value
107
124
  ```
108
125
 
109
- If you want to get a number hash you can use the `hashToNumber` function:
126
+ ## Sync Hashing (Non-Cryptographic Algorithms)
127
+
128
+ Use `hashSync()` and `hashToNumberSync()` for faster, non-cryptographic algorithms like DJB2, FNV1, MURMER, and CRC32:
110
129
 
111
130
  ```typescript
112
- import { hash, hashToNumber } from '@cacheable/utils';
131
+ import { hashSync, hashToNumberSync, HashAlgorithm } from '@cacheable/utils';
132
+
133
+ // Hash using DJB2 (default for sync)
134
+ const key = hashSync('my-cache-key');
135
+ console.log(key); // Unique hash for 'my-cache-key'
136
+
137
+ // Hash with specific algorithm
138
+ const fnv1Hash = hashSync('my-data', { algorithm: HashAlgorithm.FNV1 });
113
139
 
140
+ // Convert hash to number within range
114
141
  const min = 0;
115
142
  const max = 10;
116
-
117
- const result = hashToNumber({foo: 'bar'}, min, max, HashAlgorithm.DJB2);
143
+ const result = hashToNumberSync({foo: 'bar'}, { min, max, algorithm: HashAlgorithm.DJB2 });
118
144
  console.log(result); // A number between 0 and 10 based on the hash value
119
145
  ```
120
146
 
147
+ ## Available Hash Algorithms
148
+
149
+ **Cryptographic (Async):**
150
+ - `HashAlgorithm.SHA256` - SHA-256 (default for async methods)
151
+ - `HashAlgorithm.SHA384` - SHA-384
152
+ - `HashAlgorithm.SHA512` - SHA-512
153
+
154
+ **Non-Cryptographic (Sync):**
155
+ - `HashAlgorithm.DJB2` - DJB2 (default for sync methods)
156
+ - `HashAlgorithm.FNV1` - FNV-1
157
+ - `HashAlgorithm.MURMER` - Murmur hash
158
+ - `HashAlgorithm.CRC32` - CRC32
159
+
121
160
  # Shorthand Time Helpers
122
161
 
123
162
  The `@cacheable/utils` package provides a shorthand function to convert human-readable time strings into milliseconds. This is useful for setting time-to-live (TTL) values in caching operations.
@@ -335,6 +374,141 @@ This utility is particularly useful for:
335
374
  - **Configuration parsing** - Validating that configuration values are objects
336
375
  - **Data filtering** - Separating objects from other data types
337
376
 
377
+ # Wrap / Memoization for Sync and Async Functions
378
+
379
+ The `@cacheable/utils` package provides two main functions: `wrap` and `wrapSync`. These functions are used to memoize asynchronous and synchronous functions, respectively.
380
+
381
+ ```javascript
382
+ import { Cacheable } from 'cacheable';
383
+ const asyncFunction = async (value: number) => {
384
+ return Math.random() * value;
385
+ };
386
+
387
+ const cache = new Cacheable();
388
+ const options = {
389
+ ttl: '1h', // 1 hour
390
+ keyPrefix: 'p1', // key prefix. This is used if you have multiple functions and need to set a unique prefix.
391
+ cache,
392
+ }
393
+ const wrappedFunction = wrap(asyncFunction, options);
394
+ console.log(await wrappedFunction(2)); // 4
395
+ console.log(await wrappedFunction(2)); // 4 from cache
396
+ ```
397
+ 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:
398
+
399
+ ```javascript
400
+ import { Cacheable } from 'cacheable';
401
+ const asyncFunction = async (value: number) => {
402
+ return value;
403
+ };
404
+
405
+ const cache = new Cacheable();
406
+ const options = {
407
+ ttl: '1h', // 1 hour
408
+ keyPrefix: 'p1', // key prefix. This is used if you have multiple functions and need to set a unique prefix.
409
+ cache,
410
+ }
411
+
412
+ const wrappedFunction = wrap(asyncFunction, options);
413
+ const promises = [];
414
+ for (let i = 0; i < 10; i++) {
415
+ promises.push(wrappedFunction(i));
416
+ }
417
+
418
+ const results = await Promise.all(promises); // all results should be the same
419
+
420
+ console.log(results); // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
421
+ ```
422
+
423
+ 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:
424
+
425
+ ```javascript
426
+ import { CacheableMemory } from 'cacheable';
427
+ const syncFunction = (value: number) => {
428
+ return value * 2;
429
+ };
430
+
431
+ const cache = new CacheableMemory();
432
+ const wrappedFunction = wrap(syncFunction, { ttl: '1h', key: 'syncFunction', cache });
433
+ console.log(wrappedFunction(2)); // 4
434
+ console.log(wrappedFunction(2)); // 4 from cache
435
+ ```
436
+
437
+ 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.
438
+
439
+ 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.
440
+
441
+ ```javascript
442
+ import { CacheableMemory } from 'cacheable';
443
+ const syncFunction = (value: number) => {
444
+ throw new Error('error');
445
+ };
446
+
447
+ const cache = new CacheableMemory();
448
+ const wrappedFunction = wrap(syncFunction, { ttl: '1h', key: 'syncFunction', cacheError: true, cache });
449
+ console.log(wrappedFunction()); // error
450
+ console.log(wrappedFunction()); // error from cache
451
+ ```
452
+
453
+ 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.
454
+
455
+ ```javascript
456
+ const cache = new Cacheable();
457
+ const options: WrapOptions = {
458
+ cache,
459
+ keyPrefix: 'test',
460
+ createKey: (function_, arguments_, options: WrapOptions) => `customKey:${options?.keyPrefix}:${arguments_[0]}`,
461
+ };
462
+
463
+ const wrapped = wrap((argument: string) => `Result for ${argument}`, options);
464
+
465
+ const result1 = await wrapped('arg1');
466
+ const result2 = await wrapped('arg1'); // Should hit the cache
467
+
468
+ console.log(result1); // Result for arg1
469
+ console.log(result2); // Result for arg1 (from cache)
470
+ ```
471
+
472
+ 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.
473
+
474
+ # Get Or Set Memoization Function
475
+
476
+ 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:
477
+
478
+ ```typescript
479
+ export type GetOrSetFunctionOptions = {
480
+ ttl?: number | string;
481
+ cacheErrors?: boolean;
482
+ throwErrors?: boolean;
483
+ };
484
+ ```
485
+
486
+ Here is an example of how to use the `getOrSet` method:
487
+
488
+ ```javascript
489
+ import { Cacheable } from 'cacheable';
490
+ const cache = new Cacheable();
491
+ // Use getOrSet to fetch user data
492
+ const function_ = async () => Math.random() * 100;
493
+ const value = await getOrSet('randomValue', function_, { ttl: '1h', cache });
494
+ console.log(value); // e.g. 42.123456789
495
+ ```
496
+
497
+ You can also use a function to compute the key for the function:
498
+
499
+ ```javascript
500
+ import { Cacheable, GetOrSetOptions } from 'cacheable';
501
+ const cache = new Cacheable();
502
+
503
+ // Function to generate a key based on options
504
+ const generateKey = (options?: GetOrSetOptions) => {
505
+ return `custom_key_:${options?.cacheId || 'default'}`;
506
+ };
507
+
508
+ const function_ = async () => Math.random() * 100;
509
+ const value = await getOrSet(generateKey(), function_, { ttl: '1h', cache });
510
+ ```
511
+
338
512
  # How to Contribute
339
513
 
340
514
  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`.