cache-manager 5.7.6 → 6.0.1
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/LICENSE +1 -1
- package/README.md +287 -240
- package/dist/index.cjs +294 -0
- package/dist/index.d.cts +76 -0
- package/dist/index.d.ts +76 -3
- package/dist/index.js +257 -19
- package/package.json +43 -48
- package/dist/caching.d.ts +0 -60
- package/dist/caching.js +0 -101
- package/dist/multi-caching.d.ts +0 -6
- package/dist/multi-caching.js +0 -129
- package/dist/stores/index.d.ts +0 -1
- package/dist/stores/index.js +0 -18
- package/dist/stores/memory.d.ts +0 -22
- package/dist/stores/memory.js +0 -90
- package/dist/utils.d.ts +0 -8
- package/dist/utils.js +0 -20
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
[<img align="center" src="https://
|
|
1
|
+
[<img align="center" src="https://cacheable.org/logo.svg" alt="Cacheable" />](https://github.com/jaredwray/cacheable)
|
|
2
2
|
|
|
3
3
|
# cache-manager
|
|
4
4
|
[](https://codecov.io/gh/jaredwray/cacheable)
|
|
@@ -7,340 +7,387 @@
|
|
|
7
7
|
[](https://npmjs.com/package/cache-manager)
|
|
8
8
|

|
|
9
9
|
|
|
10
|
-
#
|
|
10
|
+
# Simple and fast NodeJS caching module.
|
|
11
|
+
A cache module for NodeJS that allows easy wrapping of functions in cache, tiered caches, and a consistent interface.
|
|
12
|
+
- Made with Typescript and compatible with [ESModules](https://nodejs.org/docs/latest-v14.x/api/esm.html).
|
|
13
|
+
- Easy way to wrap any function in cache, supports a mechanism to refresh expiring cache keys in background.
|
|
14
|
+
- Tiered caches -- data gets stored in each cache and fetched from the highest priority cache(s) first.
|
|
15
|
+
- Use with any [Keyv](https://keyv.org/) compatible storage adapter.
|
|
16
|
+
- 100% test coverage via [vitest](https://github.com/vitest-dev/vitest).
|
|
17
|
+
|
|
18
|
+
We moved to using [Keyv](https://keyv.org/) which are more actively maintained and have a larger community.
|
|
11
19
|
|
|
12
|
-
A
|
|
20
|
+
A special thanks to [Tim Phan](https://github.com/timphandev) who tooke `cache-manager` v5 and ported it to [Keyv](https://keyv.org/) which is the foundation of v6. 🎉 Another special thanks to [Doug Ayers](https://github.com/douglascayers) who wrote `promise-coalesce` which was used in v5 and now embedded in v6.
|
|
21
|
+
|
|
22
|
+
If you are looking for older documentation you can find it here:
|
|
23
|
+
* [v5 Documentation](https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/READMEv5.md)
|
|
24
|
+
* [v4 Documentation](https://github.com/jaredwray/cacheable/blob/main/packages/cache-manager/READMEv4.md)
|
|
13
25
|
|
|
14
26
|
## Table of Contents
|
|
15
|
-
* [Features](#features)
|
|
16
27
|
* [Installation](#installation)
|
|
17
|
-
* [
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
* [
|
|
21
|
-
* [
|
|
22
|
-
* [
|
|
23
|
-
* [
|
|
24
|
-
* [
|
|
28
|
+
* [Quick start](#quick-start)
|
|
29
|
+
* [Using `CacheableMemory` or `lru-cache` as storage adapter](#using-cacheablememory-or-lru-cache-as-storage-adapter)
|
|
30
|
+
* [Methods](#methods)
|
|
31
|
+
* [.set](#set)
|
|
32
|
+
* [.mset](#mset)
|
|
33
|
+
* [.get](#get)
|
|
34
|
+
* [.mget](#mget)
|
|
35
|
+
* [.del](#del)
|
|
36
|
+
* [.mdel](#mdel)
|
|
37
|
+
* [.clear](#clear)
|
|
38
|
+
* [.wrap](#wrap)
|
|
39
|
+
* [Events](#events)
|
|
40
|
+
* [.set](#set)
|
|
41
|
+
* [.del](#del)
|
|
42
|
+
* [.clear](#clear)
|
|
43
|
+
* [.refresh](#refresh)
|
|
44
|
+
* [Update on `redis` and `ioredis` Support](#update-on-redis-and-ioredis-support)
|
|
45
|
+
* [Using Legacy Storage Adapters](#using-legacy-storage-adapters)
|
|
25
46
|
* [Contribute](#contribute)
|
|
26
47
|
* [License](#license)
|
|
27
48
|
|
|
28
|
-
## Features
|
|
29
|
-
|
|
30
|
-
- Made with Typescript and compatible with [ESModules](https://nodejs.org/docs/latest-v14.x/api/esm.html)
|
|
31
|
-
- Easy way to wrap any function in cache.
|
|
32
|
-
- Tiered caches -- data gets stored in each cache and fetched from the highest.
|
|
33
|
-
priority cache(s) first.
|
|
34
|
-
- Use any cache you want, as long as it has the same API.
|
|
35
|
-
- 100% test coverage via [vitest](https://github.com/vitest-dev/vitest).
|
|
36
|
-
|
|
37
49
|
## Installation
|
|
38
50
|
|
|
39
|
-
|
|
51
|
+
```sh
|
|
52
|
+
npm install cache-manager
|
|
53
|
+
```
|
|
40
54
|
|
|
41
|
-
|
|
55
|
+
By default, everything is stored in memory; you can optionally also install a storage adapter; choose one from any of the storage adapters supported by Keyv:
|
|
42
56
|
|
|
43
|
-
|
|
57
|
+
```sh
|
|
58
|
+
npm install @keyv/redis
|
|
59
|
+
npm install @keyv/memcache
|
|
60
|
+
npm install @keyv/mongo
|
|
61
|
+
npm install @keyv/sqlite
|
|
62
|
+
npm install @keyv/postgres
|
|
63
|
+
npm install @keyv/mysql
|
|
64
|
+
npm install @keyv/etcd
|
|
65
|
+
```
|
|
66
|
+
In addition Keyv supports other storage adapters such as `lru-cache` and `CacheableMemory` from Cacheable (more examples below). Please read [Keyv document](https://keyv.org/docs/) for more information.
|
|
44
67
|
|
|
68
|
+
## Quick start
|
|
45
69
|
```typescript
|
|
46
|
-
import {
|
|
70
|
+
import { Keyv } from 'keyv';
|
|
71
|
+
import { createCache } from 'cache-manager';
|
|
47
72
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
73
|
+
// Memory store by default
|
|
74
|
+
const cache = createCache()
|
|
75
|
+
|
|
76
|
+
// Single store which is in memory
|
|
77
|
+
const cache = createCache({
|
|
78
|
+
stores: [new Keyv()],
|
|
79
|
+
})
|
|
80
|
+
```
|
|
81
|
+
Here is an example of doing layer 1 and layer 2 caching with the in-memory being `CacheableMemory` from Cacheable and the second layer being `@keyv/redis`:
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { Keyv } from 'keyv';
|
|
85
|
+
import { KeyvRedis } from '@keyv/redis';
|
|
86
|
+
import { CacheableMemory } from 'cacheable';
|
|
87
|
+
import { createCache } from 'cache-manager';
|
|
88
|
+
|
|
89
|
+
// Multiple stores
|
|
90
|
+
const cache = createCache({
|
|
91
|
+
stores: [
|
|
92
|
+
// High performance in-memory cache with LRU and TTL
|
|
93
|
+
new Keyv({
|
|
94
|
+
store: new CacheableMemory({ ttl: 60000, lruSize: 5000 }),
|
|
95
|
+
}),
|
|
96
|
+
|
|
97
|
+
// Redis Store
|
|
98
|
+
new Keyv({
|
|
99
|
+
store: new KeyvRedis('redis://user:pass@localhost:6379'),
|
|
100
|
+
}),
|
|
101
|
+
],
|
|
102
|
+
})
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Once it is created, you can use the cache object to set, get, delete, and wrap functions in cache.
|
|
52
106
|
|
|
53
|
-
|
|
54
|
-
await memoryCache.set('foo', 'bar', ttl);
|
|
107
|
+
```ts
|
|
55
108
|
|
|
56
|
-
|
|
57
|
-
|
|
109
|
+
// With default ttl and refreshThreshold
|
|
110
|
+
const cache = createCache({
|
|
111
|
+
ttl: 10000,
|
|
112
|
+
refreshThreshold: 3000,
|
|
113
|
+
})
|
|
58
114
|
|
|
59
|
-
await
|
|
115
|
+
await cache.set('foo', 'bar')
|
|
116
|
+
// => bar
|
|
60
117
|
|
|
61
|
-
|
|
62
|
-
//
|
|
118
|
+
await cache.get('foo')
|
|
119
|
+
// => bar
|
|
63
120
|
|
|
64
|
-
|
|
121
|
+
await cache.del('foo')
|
|
122
|
+
// => true
|
|
65
123
|
|
|
66
|
-
|
|
67
|
-
|
|
124
|
+
await cache.get('foo')
|
|
125
|
+
// => null
|
|
68
126
|
|
|
69
|
-
|
|
70
|
-
//
|
|
127
|
+
await cache.wrap('key', () => 'value')
|
|
128
|
+
// => value
|
|
71
129
|
```
|
|
72
130
|
|
|
73
|
-
|
|
131
|
+
## Using `CacheableMemory` or `lru-cache` as storage adapter
|
|
74
132
|
|
|
75
|
-
|
|
133
|
+
Because we are using [Keyv](https://keyv.org/), you can use any storage adapter that Keyv supports such as `lru-cache` or `CacheableMemory` from Cacheable. Below is an example of using `CacheableMemory`:
|
|
76
134
|
|
|
77
|
-
|
|
78
|
-
await memoryCache.store.mset(
|
|
79
|
-
[
|
|
80
|
-
['foo', 'bar'],
|
|
81
|
-
['foo2', 'bar2'],
|
|
82
|
-
],
|
|
83
|
-
ttl,
|
|
84
|
-
);
|
|
135
|
+
In this example we are using `CacheableMemory` from Cacheable which is a fast in-memory cache that supports LRU and and TTL expiration.
|
|
85
136
|
|
|
86
|
-
|
|
87
|
-
|
|
137
|
+
```ts
|
|
138
|
+
import { createCache } from 'cache-manager';
|
|
139
|
+
import {Keyv} from 'keyv';
|
|
140
|
+
import { CacheableMemory } from 'cacheable';
|
|
88
141
|
|
|
89
|
-
|
|
90
|
-
|
|
142
|
+
const keyv = new Keyv({ store: new CacheableMemory({ ttl: 60000, lruSize: 5000 }) });
|
|
143
|
+
const cache = createCache({ stores: [keyv] });
|
|
91
144
|
```
|
|
92
145
|
|
|
93
|
-
|
|
146
|
+
Here is an example using `lru-cache`:
|
|
94
147
|
|
|
95
|
-
|
|
148
|
+
```ts
|
|
149
|
+
import { createCache } from 'cache-manager';
|
|
150
|
+
import { Keyv } from 'keyv';
|
|
151
|
+
import { LRU } from 'lru-cache';
|
|
96
152
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
153
|
+
const keyv = new Keyv({ store: new LRU({ max: 5000, maxAge: 60000 }) });
|
|
154
|
+
const cache = createCache({ stores: [keyv] });
|
|
155
|
+
```
|
|
100
156
|
|
|
101
|
-
|
|
157
|
+
### Options
|
|
158
|
+
- **stores**?: Keyv[]
|
|
102
159
|
|
|
103
|
-
|
|
160
|
+
List of Keyv instance. Please refer to the [Keyv document](https://keyv.org/docs/#3.-create-a-new-keyv-instance) for more information.
|
|
161
|
+
- **ttl**?: number - Default time to live in milliseconds.
|
|
104
162
|
|
|
105
|
-
|
|
163
|
+
The time to live in milliseconds. This is the maximum amount of time that an item can be in the cache before it is removed.
|
|
164
|
+
- **refreshThreshold**?: number - Default refreshThreshold in milliseconds.
|
|
106
165
|
|
|
107
|
-
|
|
108
|
-
import { createCache, memoryStore } from 'cache-manager';
|
|
109
|
-
|
|
110
|
-
// Create memory cache synchronously
|
|
111
|
-
const memoryCache = createCache(memoryStore({
|
|
112
|
-
max: 100,
|
|
113
|
-
ttl: 10 * 1000 /*milliseconds*/,
|
|
114
|
-
}));
|
|
115
|
-
|
|
116
|
-
// Default parameter in function
|
|
117
|
-
function myService(cache = createCache(memoryStore())) {}
|
|
118
|
-
|
|
119
|
-
// Default parameter in class constructor
|
|
120
|
-
const DEFAULT_CACHE = createCache(memoryStore(), { ttl: 60 * 1000 });
|
|
121
|
-
// ...
|
|
122
|
-
class MyService {
|
|
123
|
-
constructor(private cache = DEFAULT_CACHE) {}
|
|
124
|
-
}
|
|
125
|
-
```
|
|
166
|
+
If the remaining TTL is less than **refreshThreshold**, the system will update the value asynchronously in background.
|
|
126
167
|
|
|
127
|
-
|
|
168
|
+
## Methods
|
|
169
|
+
### set
|
|
170
|
+
`set(key, value, [ttl]): Promise<value>`
|
|
128
171
|
|
|
129
|
-
|
|
130
|
-
|
|
172
|
+
Sets a key value pair. It is possible to define a ttl (in miliseconds). An error will be throw on any failed
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
await cache.set('key-1', 'value 1')
|
|
131
176
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
177
|
+
// expires after 5 seconds
|
|
178
|
+
await cache.set('key 2', 'value 2', 5000)
|
|
179
|
+
```
|
|
180
|
+
See unit tests in [`test/set.test.ts`](./test/set.test.ts) for more information.
|
|
136
181
|
|
|
137
|
-
|
|
138
|
-
await multiCache.set('foo2', 'bar2', ttl);
|
|
182
|
+
### mset
|
|
139
183
|
|
|
140
|
-
|
|
141
|
-
console.log(await multiCache.get('foo2'));
|
|
142
|
-
// >> "bar2"
|
|
184
|
+
`mset(keys: [ { key, value, ttl } ]): Promise<true>`
|
|
143
185
|
|
|
144
|
-
|
|
145
|
-
await multiCache.del('foo2');
|
|
186
|
+
Sets multiple key value pairs. It is possible to define a ttl (in miliseconds). An error will be throw on any failed
|
|
146
187
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
['foo2', 'bar2'],
|
|
153
|
-
],
|
|
154
|
-
ttl
|
|
155
|
-
);
|
|
156
|
-
|
|
157
|
-
// mget() fetches from highest priority cache.
|
|
158
|
-
// If the first cache does not return all the keys,
|
|
159
|
-
// the next cache is fetched with the keys that were not found.
|
|
160
|
-
// This is done recursively until either:
|
|
161
|
-
// - all have been found
|
|
162
|
-
// - all caches has been fetched
|
|
163
|
-
console.log(await multiCache.mget('key', 'key2'));
|
|
164
|
-
// >> ['bar', 'bar2']
|
|
165
|
-
|
|
166
|
-
// Delete keys with mdel() passing arguments...
|
|
167
|
-
await multiCache.mdel('foo', 'foo2');
|
|
188
|
+
```ts
|
|
189
|
+
await cache.mset([
|
|
190
|
+
{ key: 'key-1', value: 'value 1' },
|
|
191
|
+
{ key: 'key-2', value: 'value 2', ttl: 5000 },
|
|
192
|
+
]);
|
|
168
193
|
```
|
|
169
194
|
|
|
170
|
-
|
|
195
|
+
### get
|
|
196
|
+
`get(key): Promise<value>`
|
|
171
197
|
|
|
172
|
-
|
|
198
|
+
Gets a saved value from the cache. Returns a null if not found or expired. If the value was found it returns the value.
|
|
173
199
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
* refreshThreshold: discussed in details below.
|
|
177
|
-
* isCacheable: a function to determine whether the value is cacheable or not.
|
|
178
|
-
* onBackgroundRefreshError: a function to handle errors that occur during background refresh.
|
|
200
|
+
```ts
|
|
201
|
+
await cache.set('key', 'value')
|
|
179
202
|
|
|
180
|
-
|
|
181
|
-
|
|
203
|
+
await cache.get('key')
|
|
204
|
+
// => value
|
|
182
205
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
ttl: 10 * 1000 /*milliseconds*/,
|
|
186
|
-
shouldCloneBeforeSet: false, // this is set true by default (optional)
|
|
187
|
-
});
|
|
206
|
+
await cache.get('foo')
|
|
207
|
+
// => null
|
|
188
208
|
```
|
|
209
|
+
See unit tests in [`test/get.test.ts`](./test/get.test.ts) for more information.
|
|
189
210
|
|
|
190
|
-
|
|
191
|
-
* max: The maximum number of items that can be stored in the cache. If the cache is full, the least recently used item is removed.
|
|
192
|
-
* shouldCloneBeforeSet: If true, the value will be cloned before being set in the cache. This is set to `true` by default.
|
|
211
|
+
### mget
|
|
193
212
|
|
|
194
|
-
|
|
213
|
+
`mget(keys: [key]): Promise<value[]>`
|
|
195
214
|
|
|
196
|
-
|
|
197
|
-
This is done by adding a `refreshThreshold` attribute while creating the caching store or passing it to the `wrap` function.
|
|
215
|
+
Gets multiple saved values from the cache. Returns a null if not found or expired. If the value was found it returns the value.
|
|
198
216
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
217
|
+
```ts
|
|
218
|
+
await cache.mset([
|
|
219
|
+
{ key: 'key-1', value: 'value 1' },
|
|
220
|
+
{ key: 'key-2', value: 'value 2' },
|
|
221
|
+
]);
|
|
202
222
|
|
|
203
|
-
|
|
223
|
+
await cache.mget(['key-1', 'key-2', 'key-3'])
|
|
224
|
+
// => ['value 1', 'value 2', null]
|
|
225
|
+
```
|
|
204
226
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
* The background refresh mechanism currently does not support providing multiple keys to `wrap` function.
|
|
208
|
-
* If no `ttl` is set for the key, the refresh mechanism will not be triggered. For redis, the `ttl` is set to -1 by default.
|
|
227
|
+
### del
|
|
228
|
+
`del(key): Promise<true>`
|
|
209
229
|
|
|
210
|
-
|
|
230
|
+
Delete a key, an error will be throw on any failed.
|
|
211
231
|
|
|
212
|
-
```
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
232
|
+
```ts
|
|
233
|
+
await cache.set('key', 'value')
|
|
234
|
+
|
|
235
|
+
await cache.get('key')
|
|
236
|
+
// => value
|
|
237
|
+
|
|
238
|
+
await cache.del('key')
|
|
239
|
+
|
|
240
|
+
await cache.get('key')
|
|
241
|
+
// => null
|
|
222
242
|
```
|
|
243
|
+
See unit tests in [`test/del.test.ts`](./test/del.test.ts) for more information.
|
|
223
244
|
|
|
224
|
-
|
|
245
|
+
### mdel
|
|
225
246
|
|
|
226
|
-
|
|
247
|
+
`mdel(keys: [key]): Promise<true>`
|
|
227
248
|
|
|
228
|
-
|
|
249
|
+
Delete multiple keys, an error will be throw on any failed.
|
|
229
250
|
|
|
230
|
-
```
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
251
|
+
```ts
|
|
252
|
+
await cache.mset([
|
|
253
|
+
{ key: 'key-1', value: 'value 1' },
|
|
254
|
+
{ key: 'key-2', value: 'value 2' },
|
|
255
|
+
]);
|
|
256
|
+
|
|
257
|
+
await cache.mdel(['key-1', 'key-2'])
|
|
235
258
|
```
|
|
236
259
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
While this behaviour can prevent additional calls to downstream resources, it can also slow down the response time.
|
|
240
|
-
This can be changed by setting the `nonBlockingSet` option to `true`.
|
|
241
|
-
Doing will make the function return before the value is set in the cache.
|
|
242
|
-
The setting applies to both single and multi caches.
|
|
260
|
+
### clear
|
|
261
|
+
`clear(): Promise<true>`
|
|
243
262
|
|
|
244
|
-
|
|
245
|
-
|
|
263
|
+
Flush all data, an error will be throw on any failed.
|
|
264
|
+
|
|
265
|
+
```ts
|
|
266
|
+
await cache.set('key-1', 'value 1')
|
|
267
|
+
await cache.set('key-2', 'value 2')
|
|
268
|
+
|
|
269
|
+
await cache.get('key-1')
|
|
270
|
+
// => value 1
|
|
271
|
+
await cache.get('key-2')
|
|
272
|
+
// => value 2
|
|
273
|
+
|
|
274
|
+
await cache.clear()
|
|
275
|
+
|
|
276
|
+
await cache.get('key-1')
|
|
277
|
+
// => null
|
|
278
|
+
await cache.get('key-2')
|
|
279
|
+
// => null
|
|
246
280
|
```
|
|
281
|
+
See unit tests in [`test/clear.test.ts`](./test/clear.test.ts) for more information.
|
|
247
282
|
|
|
248
|
-
|
|
283
|
+
### wrap
|
|
284
|
+
`wrap(key, fn: async () => value, [ttl], [refreshThreshold]): Promise<value>`
|
|
249
285
|
|
|
250
|
-
|
|
286
|
+
Wraps a function in cache. The first time the function is run, its results are stored in cache so subsequent calls retrieve from cache instead of calling the function.
|
|
287
|
+
|
|
288
|
+
If `refreshThreshold` is set and the remaining TTL is less than `refreshThreshold`, the system will update the value asynchronously. In the meantime, the system will return the old value until expiration.
|
|
251
289
|
|
|
252
290
|
```typescript
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
// The memory cache is initialized using cache-manager with a maximum of 100 items and a TTL (time-to-live) of 10 seconds:
|
|
258
|
-
const memoryCache = await caching('memory', {
|
|
259
|
-
max: 100,
|
|
260
|
-
ttl: 10 * 1000 /*milliseconds*/
|
|
261
|
-
});
|
|
291
|
+
await cache.wrap('key', () => 1, 5000, 3000)
|
|
292
|
+
// call function then save the result to cache
|
|
293
|
+
// => 1
|
|
262
294
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
// A middleware function is defined to check the cache before processing the request. If the response is found in the cache, it is returned immediately. If not, the request proceeds to the route handler, and the response is cached before being sent:
|
|
267
|
-
const cacheMiddleware = async (req, res, next) => {
|
|
268
|
-
const key = req.originalUrl;
|
|
269
|
-
|
|
270
|
-
try {
|
|
271
|
-
const cachedResponse = await memoryCache.get(key);
|
|
272
|
-
if (cachedResponse) {
|
|
273
|
-
// Cache hit, return the cached response
|
|
274
|
-
return res.send(cachedResponse);
|
|
275
|
-
} else {
|
|
276
|
-
// Cache miss, proceed to the route handler
|
|
277
|
-
res.sendResponse = res.send;
|
|
278
|
-
res.send = async (body) => {
|
|
279
|
-
// Store the response in cache
|
|
280
|
-
await memoryCache.set(key, body);
|
|
281
|
-
res.sendResponse(body);
|
|
282
|
-
};
|
|
283
|
-
next();
|
|
284
|
-
}
|
|
285
|
-
} catch (err) {
|
|
286
|
-
next(err);
|
|
287
|
-
}
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
// The cacheMiddleware is applied to the /data route, which simulates a slow database call with a 2-second delay:
|
|
291
|
-
app.get('/data', cacheMiddleware, (req, res) => {
|
|
292
|
-
// Simulate a slow database call
|
|
293
|
-
setTimeout(() => {
|
|
294
|
-
res.send({ data: 'This is some data', timestamp: new Date() });
|
|
295
|
-
}, 2000); // 2 seconds delay
|
|
296
|
-
});
|
|
295
|
+
await cache.wrap('key', () => 2, 5000, 3000)
|
|
296
|
+
// return data from cache, function will not be called again
|
|
297
|
+
// => 1
|
|
297
298
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
299
|
+
// wait 3 seconds
|
|
300
|
+
await sleep(3000)
|
|
301
|
+
|
|
302
|
+
await cache.wrap('key', () => 2, 5000, 3000)
|
|
303
|
+
// return data from cache, call function in background and save the result to cache
|
|
304
|
+
// => 1
|
|
305
|
+
|
|
306
|
+
await cache.wrap('key', () => 3, 5000, 3000)
|
|
307
|
+
// return data from cache, function will not be called
|
|
308
|
+
// => 2
|
|
301
309
|
|
|
310
|
+
await cache.wrap('error', () => {
|
|
311
|
+
throw new Error('failed')
|
|
312
|
+
})
|
|
313
|
+
// => error
|
|
302
314
|
```
|
|
315
|
+
**NOTES:**
|
|
303
316
|
|
|
304
|
-
|
|
317
|
+
* The store that will be checked for refresh is the one where the key will be found first (highest priority).
|
|
318
|
+
* If the threshold is low and the worker function is slow, the key may expire and you may encounter a racing condition with updating values.
|
|
319
|
+
* If no `ttl` is set for the key, the refresh mechanism will not be triggered.
|
|
305
320
|
|
|
306
|
-
|
|
321
|
+
See unit tests in [`test/wrap.test.ts`](./test/wrap.test.ts) for more information.
|
|
307
322
|
|
|
308
|
-
|
|
323
|
+
## Events
|
|
324
|
+
### set
|
|
325
|
+
Fired when a key has been added or changed.
|
|
309
326
|
|
|
310
|
-
|
|
327
|
+
```ts
|
|
328
|
+
cache.on('set', ({ key, value, error }) => {
|
|
329
|
+
// ... do something ...
|
|
330
|
+
})
|
|
331
|
+
```
|
|
311
332
|
|
|
312
|
-
###
|
|
333
|
+
### del
|
|
334
|
+
Fired when a key has been removed manually.
|
|
313
335
|
|
|
314
|
-
|
|
336
|
+
```ts
|
|
337
|
+
cache.on('del', ({ key, error }) => {
|
|
338
|
+
// ... do something ...
|
|
339
|
+
})
|
|
340
|
+
```
|
|
315
341
|
|
|
316
|
-
|
|
342
|
+
### clear
|
|
343
|
+
Fired when the cache has been flushed.
|
|
317
344
|
|
|
318
|
-
|
|
345
|
+
```ts
|
|
346
|
+
cache.on('clear', (error) => {
|
|
347
|
+
if (error) {
|
|
348
|
+
// ... do something ...
|
|
349
|
+
}
|
|
350
|
+
})
|
|
351
|
+
```
|
|
319
352
|
|
|
320
|
-
|
|
353
|
+
### refresh
|
|
354
|
+
Fired when the cache has been refreshed in the background.
|
|
321
355
|
|
|
322
|
-
|
|
356
|
+
```ts
|
|
357
|
+
cache.on('refresh', ({ key, value, error }) => {
|
|
358
|
+
if (error) {
|
|
359
|
+
// ... do something ...
|
|
360
|
+
}
|
|
361
|
+
})
|
|
362
|
+
```
|
|
323
363
|
|
|
324
|
-
|
|
364
|
+
See unit tests in [`test/events.test.ts`](./test/events.test.ts) for more information.
|
|
325
365
|
|
|
326
|
-
|
|
366
|
+
## Update on `redis` and `ioredis` Support
|
|
327
367
|
|
|
328
|
-
|
|
368
|
+
We will not be supporting `cache-manager-ioredis-yet` or `cache-manager-redis-yet` in the future as we have moved to using `Keyv` as the storage adapter `@keyv/redis`.
|
|
329
369
|
|
|
330
|
-
|
|
370
|
+
## Using Legacy Storage Adapters
|
|
331
371
|
|
|
332
|
-
|
|
372
|
+
There are many storage adapters built for `cache-manager` and because of that we wanted to provide a way to use them with `KeyvAdapter`. Below is an example of using `cache-manager-redis-yet`:
|
|
333
373
|
|
|
334
|
-
|
|
374
|
+
```ts
|
|
375
|
+
import { createCache, KeyvAdapter } from 'cache-manager';
|
|
376
|
+
import { Keyv } from 'keyv';
|
|
377
|
+
import { redisStore } from 'cache-manager-redis-yet';
|
|
335
378
|
|
|
336
|
-
|
|
379
|
+
const adapter = new KeyvAdapter( await redisStore() );
|
|
380
|
+
const cache = createCache({
|
|
381
|
+
stores: [new Keyv({ store: adapter })],
|
|
382
|
+
});
|
|
383
|
+
```
|
|
337
384
|
|
|
338
|
-
|
|
385
|
+
This adapter will allow you to add in any storage adapter. If there are issues it needs to follow `CacheManagerStore` interface.
|
|
339
386
|
|
|
340
387
|
## Contribute
|
|
341
388
|
|
|
342
|
-
If you would like to contribute to the project, please read how to contribute here [CONTRIBUTING.md](
|
|
389
|
+
If you would like to contribute to the project, please read how to contribute here [CONTRIBUTING.md](https://github.com/jaredwray/cacheable/blob/main/CONTRIBUTING.md).
|
|
343
390
|
|
|
344
391
|
## License
|
|
345
392
|
|
|
346
|
-
|
|
393
|
+
[MIT © Jared Wray ](./LICENSE)
|