cache-manager 5.4.0 → 5.5.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 +57 -6
- package/dist/caching.d.ts +15 -13
- package/dist/caching.js +43 -23
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -3
- package/dist/multi-caching.d.ts +1 -1
- package/dist/multi-caching.js +50 -32
- package/dist/stores/index.d.ts +1 -1
- package/dist/stores/index.js +1 -1
- package/dist/stores/memory.d.ts +4 -4
- package/dist/stores/memory.js +36 -27
- package/package.json +23 -30
- package/READMEv4.md +0 -542
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# node-cache-manager
|
|
2
|
-
[](https://codecov.io/gh/node-cache-manager/cache-manager)
|
|
3
|
+
[](https://github.com/node-cache-manager/cache-manager/actions/workflows/test.yml)
|
|
4
|
+
[](https://github.com/node-cache-manager/cache-manager/blob/main/LICENSE)
|
|
5
5
|
[](https://npmjs.com/package/cache-manager)
|
|
6
6
|

|
|
7
7
|
|
|
@@ -9,6 +9,19 @@
|
|
|
9
9
|
|
|
10
10
|
A cache module for nodejs that allows easy wrapping of functions in cache, tiered caches, and a consistent interface.
|
|
11
11
|
|
|
12
|
+
## Table of Contents
|
|
13
|
+
* [Features](#features)
|
|
14
|
+
* [Installation](#installation)
|
|
15
|
+
* [Usage Examples](#usage-examples)
|
|
16
|
+
* [Single Store](#single-store)
|
|
17
|
+
* [Multi-Store](#multi-store)
|
|
18
|
+
* [Cache Manager Options](#cache-manager-options)
|
|
19
|
+
* [Refresh cache keys in background](#refresh-cache-keys-in-background)
|
|
20
|
+
* [Error Handling](#error-handling)
|
|
21
|
+
* [Store Engines](#store-engines)
|
|
22
|
+
* [Contribute](#contribute)
|
|
23
|
+
* [License](#license)
|
|
24
|
+
|
|
12
25
|
## Features
|
|
13
26
|
|
|
14
27
|
- Made with Typescript and compatible with [ESModules](https://nodejs.org/docs/latest-v14.x/api/esm.html)
|
|
@@ -155,6 +168,23 @@ await multiCache.mdel('foo', 'foo2');
|
|
|
155
168
|
|
|
156
169
|
See unit tests in [`test/multi-caching.test.ts`](./test/multi-caching.test.ts) for more information.
|
|
157
170
|
|
|
171
|
+
### Cache Manager Options
|
|
172
|
+
|
|
173
|
+
The `caching` and `multiCaching` functions accept an options object as the second parameter. The following options are available:
|
|
174
|
+
* 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.
|
|
175
|
+
* ttl: 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.
|
|
176
|
+
* shouldCloneBeforeSet: If true, the value will be cloned before being set in the cache. This is set to `true` by default.
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
import { caching } from 'cache-manager';
|
|
180
|
+
|
|
181
|
+
const memoryCache = await caching('memory', {
|
|
182
|
+
max: 100,
|
|
183
|
+
ttl: 10 * 1000 /*milliseconds*/,
|
|
184
|
+
shouldCloneBeforeSet: false, // this is set true by default (optional)
|
|
185
|
+
});
|
|
186
|
+
```
|
|
187
|
+
|
|
158
188
|
### Refresh cache keys in background
|
|
159
189
|
|
|
160
190
|
Both the `caching` and `multicaching` modules support a mechanism to refresh expiring cache keys in background when using the `wrap` function.
|
|
@@ -178,11 +208,31 @@ const memoryCache = await caching('memory', {
|
|
|
178
208
|
max: 100,
|
|
179
209
|
ttl: 10 * 1000 /*milliseconds*/,
|
|
180
210
|
refreshThreshold: 3 * 1000 /*milliseconds*/,
|
|
211
|
+
|
|
212
|
+
/* optional, but if not set, background refresh error will be an unhandled
|
|
213
|
+
* promise rejection, which might crash your node process */
|
|
214
|
+
onBackgroundRefreshError: (error) => { /* log or otherwise handle error */ }
|
|
181
215
|
});
|
|
182
216
|
```
|
|
183
217
|
|
|
184
218
|
When a value will be retrieved from Redis with a TTL minor than 3sec, the value will be updated in the background.
|
|
185
219
|
|
|
220
|
+
## Error Handling
|
|
221
|
+
|
|
222
|
+
Cache Manager now does not throw errors by default. Instead, all errors are evented through the `error` event. Here is an example on how to use it:
|
|
223
|
+
|
|
224
|
+
```javascript
|
|
225
|
+
const memoryCache = await caching('memory', {
|
|
226
|
+
max: 100,
|
|
227
|
+
ttl: 10 * 1000 /*milliseconds*/,
|
|
228
|
+
});
|
|
229
|
+
memoryCache.on('error', (error) => {
|
|
230
|
+
console.error('Cache error:', error);
|
|
231
|
+
});
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
We also have added
|
|
235
|
+
|
|
186
236
|
## Store Engines
|
|
187
237
|
|
|
188
238
|
### Official and updated to last version
|
|
@@ -217,11 +267,12 @@ When a value will be retrieved from Redis with a TTL minor than 3sec, the value
|
|
|
217
267
|
|
|
218
268
|
- [node-cache-manager-sqlite](https://github.com/maxpert/node-cache-manager-sqlite)
|
|
219
269
|
|
|
270
|
+
- [@resolid/cache-manager-sqlite](https://github.com/huijiewei/cache-manager-sqlite) (uses [better-sqlite3](https://github.com/WiseLibs/better-sqlite3))
|
|
271
|
+
|
|
220
272
|
## Contribute
|
|
221
273
|
|
|
222
|
-
If you would like to contribute to the project, please
|
|
223
|
-
for any new features or bug fixes.
|
|
274
|
+
If you would like to contribute to the project, please read how to contribute here [CONTRIBUTING.md](./CONTRIBUTING.md).
|
|
224
275
|
|
|
225
276
|
## License
|
|
226
277
|
|
|
227
|
-
|
|
278
|
+
cache-manager is licensed under the [MIT license](./LICENSE).
|
package/dist/caching.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { MemoryCache, MemoryConfig, MemoryStore } from './stores';
|
|
1
|
+
import { type MemoryCache, type MemoryConfig, type MemoryStore } from './stores/index.js';
|
|
2
2
|
export type Config = {
|
|
3
3
|
ttl?: Milliseconds;
|
|
4
4
|
refreshThreshold?: Milliseconds;
|
|
5
|
-
isCacheable?: (
|
|
5
|
+
isCacheable?: (value: unknown) => boolean;
|
|
6
|
+
onBackgroundRefreshError?: (error: unknown) => void;
|
|
6
7
|
};
|
|
7
8
|
export type Milliseconds = number;
|
|
8
9
|
/**
|
|
@@ -14,28 +15,29 @@ export type Store = {
|
|
|
14
15
|
set<T>(key: string, data: T, ttl?: Milliseconds): Promise<void>;
|
|
15
16
|
del(key: string): Promise<void>;
|
|
16
17
|
reset(): Promise<void>;
|
|
17
|
-
mset(
|
|
18
|
-
mget(...
|
|
19
|
-
mdel(...
|
|
18
|
+
mset(arguments_: Array<[string, unknown]>, ttl?: Milliseconds): Promise<void>;
|
|
19
|
+
mget(...arguments_: string[]): Promise<unknown[]>;
|
|
20
|
+
mdel(...arguments_: string[]): Promise<void>;
|
|
20
21
|
keys(pattern?: string): Promise<string[]>;
|
|
21
22
|
ttl(key: string): Promise<number>;
|
|
22
23
|
};
|
|
23
24
|
export type StoreConfig = Config;
|
|
24
25
|
export type FactoryConfig<T> = T & Config;
|
|
25
|
-
export type FactoryStore<S extends Store, T extends
|
|
26
|
-
export type Stores<S extends Store, T extends
|
|
26
|
+
export type FactoryStore<S extends Store, T extends Record<string, unknown> = never> = (config?: FactoryConfig<T>) => S | Promise<S>;
|
|
27
|
+
export type Stores<S extends Store, T extends Record<string, unknown>> = 'memory' | Store | FactoryStore<S, T>;
|
|
27
28
|
export type CachingConfig<T> = MemoryConfig | StoreConfig | FactoryConfig<T>;
|
|
28
29
|
export type WrapTTL<T> = Milliseconds | ((v: T) => Milliseconds);
|
|
29
30
|
export type Cache<S extends Store = Store> = {
|
|
31
|
+
store: S;
|
|
30
32
|
set: (key: string, value: unknown, ttl?: Milliseconds) => Promise<void>;
|
|
31
33
|
get: <T>(key: string) => Promise<T | undefined>;
|
|
32
34
|
del: (key: string) => Promise<void>;
|
|
33
35
|
reset: () => Promise<void>;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
+
on: (event: 'error', handler: (error: Error) => void) => void;
|
|
37
|
+
wrap<T>(key: string, function_: () => Promise<T>, ttl?: WrapTTL<T>, refreshThreshold?: Milliseconds): Promise<T>;
|
|
36
38
|
};
|
|
37
|
-
export declare function caching(name: 'memory',
|
|
39
|
+
export declare function caching(name: 'memory', arguments_?: MemoryConfig): Promise<MemoryCache>;
|
|
38
40
|
export declare function caching<S extends Store>(store: S): Promise<Cache<S>>;
|
|
39
|
-
export declare function caching<S extends Store, T extends
|
|
40
|
-
export declare function createCache(store: MemoryStore,
|
|
41
|
-
export declare function createCache(store: Store,
|
|
41
|
+
export declare function caching<S extends Store, T extends Record<string, unknown> = never>(factory: FactoryStore<S, T>, arguments_?: FactoryConfig<T>): Promise<Cache<S>>;
|
|
42
|
+
export declare function createCache(store: MemoryStore, arguments_?: MemoryConfig): MemoryCache;
|
|
43
|
+
export declare function createCache(store: Store, arguments_?: Config): Cache;
|
package/dist/caching.js
CHANGED
|
@@ -1,63 +1,83 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
2
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
6
|
exports.createCache = exports.caching = void 0;
|
|
7
|
+
const eventemitter3_1 = __importDefault(require("eventemitter3"));
|
|
4
8
|
const promise_coalesce_1 = require("promise-coalesce");
|
|
5
|
-
const
|
|
9
|
+
const index_js_1 = require("./stores/index.js");
|
|
6
10
|
/**
|
|
7
11
|
* Generic caching interface that wraps any caching library with a compatible interface.
|
|
8
12
|
*/
|
|
9
|
-
async function caching(factory,
|
|
13
|
+
async function caching(factory, arguments_) {
|
|
10
14
|
if (factory === 'memory') {
|
|
11
|
-
const store = (0,
|
|
12
|
-
return createCache(store,
|
|
15
|
+
const store = (0, index_js_1.memoryStore)(arguments_);
|
|
16
|
+
return createCache(store, arguments_);
|
|
13
17
|
}
|
|
14
18
|
if (typeof factory === 'function') {
|
|
15
|
-
const store = await factory(
|
|
16
|
-
return createCache(store,
|
|
19
|
+
const store = await factory(arguments_);
|
|
20
|
+
return createCache(store, arguments_);
|
|
17
21
|
}
|
|
18
22
|
const store = factory;
|
|
19
|
-
return createCache(store,
|
|
23
|
+
return createCache(store, arguments_);
|
|
20
24
|
}
|
|
21
25
|
exports.caching = caching;
|
|
22
26
|
/**
|
|
23
27
|
* Create cache instance by store (non-async).
|
|
24
28
|
*/
|
|
25
|
-
function createCache(store,
|
|
29
|
+
function createCache(store, arguments_) {
|
|
30
|
+
const eventEmitter = new eventemitter3_1.default();
|
|
26
31
|
return {
|
|
27
32
|
/**
|
|
28
33
|
* Wraps a function in cache. I.e., the first time the function is run,
|
|
29
34
|
* its results are stored in cache so subsequent calls retrieve from cache
|
|
30
35
|
* instead of calling the function.
|
|
31
|
-
|
|
36
|
+
|
|
32
37
|
* @example
|
|
33
38
|
* const result = await cache.wrap('key', () => Promise.resolve(1));
|
|
34
39
|
*
|
|
35
40
|
*/
|
|
36
|
-
|
|
37
|
-
const refreshThresholdConfig = refreshThreshold
|
|
41
|
+
async wrap(key, function_, ttl, refreshThreshold) {
|
|
42
|
+
const refreshThresholdConfig = refreshThreshold ?? arguments_?.refreshThreshold ?? 0;
|
|
38
43
|
return (0, promise_coalesce_1.coalesceAsync)(key, async () => {
|
|
39
|
-
const value = await store.get(key)
|
|
44
|
+
const value = await store.get(key).catch(error => {
|
|
45
|
+
eventEmitter.emit('error', error);
|
|
46
|
+
});
|
|
40
47
|
if (value === undefined) {
|
|
41
|
-
const result = await
|
|
42
|
-
const
|
|
43
|
-
await store.set(key, result,
|
|
48
|
+
const result = await function_();
|
|
49
|
+
const cacheTtl = typeof ttl === 'function' ? ttl(result) : ttl;
|
|
50
|
+
await store.set(key, result, cacheTtl).catch(error => eventEmitter.emit('error', error));
|
|
44
51
|
return result;
|
|
45
52
|
}
|
|
46
|
-
|
|
47
|
-
const
|
|
53
|
+
if (refreshThresholdConfig) {
|
|
54
|
+
const cacheTtl = typeof ttl === 'function' ? ttl(value) : ttl;
|
|
48
55
|
const remainingTtl = await store.ttl(key);
|
|
49
56
|
if (remainingTtl !== -1 && remainingTtl < refreshThresholdConfig) {
|
|
50
|
-
(0, promise_coalesce_1.coalesceAsync)(`+++${key}`,
|
|
57
|
+
(0, promise_coalesce_1.coalesceAsync)(`+++${key}`, function_)
|
|
58
|
+
.then(async (result) => store.set(key, result, cacheTtl))
|
|
59
|
+
.catch(async (error) => {
|
|
60
|
+
eventEmitter.emit('error', error);
|
|
61
|
+
eventEmitter.emit('onBackgroundRefreshError', error);
|
|
62
|
+
if (arguments_?.onBackgroundRefreshError) {
|
|
63
|
+
arguments_.onBackgroundRefreshError(error);
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
// eslint-disable-next-line @typescript-eslint/no-throw-literal
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
});
|
|
51
70
|
}
|
|
52
71
|
}
|
|
53
72
|
return value;
|
|
54
73
|
});
|
|
55
74
|
},
|
|
56
|
-
store
|
|
57
|
-
del: (key) => store.del(key),
|
|
58
|
-
get: (key) => store.get(key),
|
|
59
|
-
set: (key, value, ttl) => store.set(key, value, ttl),
|
|
60
|
-
reset: () => store.reset(),
|
|
75
|
+
store,
|
|
76
|
+
del: async (key) => store.del(key),
|
|
77
|
+
get: async (key) => store.get(key),
|
|
78
|
+
set: async (key, value, ttl) => store.set(key, value, ttl),
|
|
79
|
+
reset: async () => store.reset(),
|
|
80
|
+
on: (event, handler) => eventEmitter.on('error', handler),
|
|
61
81
|
};
|
|
62
82
|
}
|
|
63
83
|
exports.createCache = createCache;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export * from './caching';
|
|
2
|
-
export * from './multi-caching';
|
|
3
|
-
export * from './stores';
|
|
1
|
+
export * from './caching.js';
|
|
2
|
+
export * from './multi-caching.js';
|
|
3
|
+
export * from './stores/index.js';
|
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
__exportStar(require("./caching"), exports);
|
|
18
|
-
__exportStar(require("./multi-caching"), exports);
|
|
19
|
-
__exportStar(require("./stores"), exports);
|
|
17
|
+
__exportStar(require("./caching.js"), exports);
|
|
18
|
+
__exportStar(require("./multi-caching.js"), exports);
|
|
19
|
+
__exportStar(require("./stores/index.js"), exports);
|
|
20
20
|
//# sourceMappingURL=index.js.map
|
package/dist/multi-caching.d.ts
CHANGED
package/dist/multi-caching.js
CHANGED
|
@@ -1,78 +1,96 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
2
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
6
|
exports.multiCaching = void 0;
|
|
7
|
+
const eventemitter3_1 = __importDefault(require("eventemitter3"));
|
|
4
8
|
/**
|
|
5
9
|
* Module that lets you specify a hierarchy of caches.
|
|
6
10
|
*/
|
|
7
11
|
function multiCaching(caches) {
|
|
12
|
+
const eventEmitter = new eventemitter3_1.default();
|
|
8
13
|
const get = async (key) => {
|
|
9
14
|
for (const cache of caches) {
|
|
10
15
|
try {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
16
|
+
// eslint-disable-next-line no-await-in-loop
|
|
17
|
+
const value = await cache.get(key);
|
|
18
|
+
if (value !== undefined) {
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
eventEmitter.emit('error', error);
|
|
14
24
|
}
|
|
15
|
-
catch (e) { }
|
|
16
25
|
}
|
|
17
26
|
};
|
|
18
27
|
const set = async (key, data, ttl) => {
|
|
19
|
-
await Promise.all(caches.map((cache) => cache.set(key, data, ttl)));
|
|
28
|
+
await Promise.all(caches.map(async (cache) => cache.set(key, data, ttl))).catch(error => eventEmitter.emit('error', error));
|
|
20
29
|
};
|
|
21
30
|
return {
|
|
22
31
|
get,
|
|
23
32
|
set,
|
|
24
|
-
|
|
25
|
-
await Promise.all(caches.map((cache) => cache.del(key)));
|
|
33
|
+
async del(key) {
|
|
34
|
+
await Promise.all(caches.map(async (cache) => cache.del(key))).catch(error => eventEmitter.emit('error', error));
|
|
26
35
|
},
|
|
27
|
-
async wrap(key,
|
|
36
|
+
async wrap(key, function_, ttl, refreshThreshold) {
|
|
28
37
|
let value;
|
|
29
38
|
let i = 0;
|
|
30
39
|
for (; i < caches.length; i++) {
|
|
31
40
|
try {
|
|
41
|
+
// eslint-disable-next-line no-await-in-loop
|
|
32
42
|
value = await caches[i].get(key);
|
|
33
|
-
if (value !== undefined)
|
|
43
|
+
if (value !== undefined) {
|
|
34
44
|
break;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
eventEmitter.emit('error', error);
|
|
35
49
|
}
|
|
36
|
-
catch (e) { }
|
|
37
50
|
}
|
|
38
51
|
if (value === undefined) {
|
|
39
|
-
const result = await
|
|
40
|
-
const
|
|
41
|
-
await set(key, result,
|
|
52
|
+
const result = await function_();
|
|
53
|
+
const cacheTtl = typeof ttl === 'function' ? ttl(result) : ttl;
|
|
54
|
+
await set(key, result, cacheTtl);
|
|
42
55
|
return result;
|
|
43
56
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
caches[i].wrap(key, fn, ttl, refreshThreshold).then(); // call wrap for store for internal refreshThreshold logic, see: src/caching.ts caching.wrap
|
|
48
|
-
}
|
|
57
|
+
const cacheTtl = typeof ttl === 'function' ? ttl(value) : ttl;
|
|
58
|
+
await Promise.all(caches.slice(0, i).map(async (cache) => cache.set(key, value, cacheTtl))).then().catch(error => eventEmitter.emit('error', error));
|
|
59
|
+
await caches[i].wrap(key, function_, ttl, refreshThreshold).then(); // Call wrap for store for internal refreshThreshold logic, see: src/caching.ts caching.wrap
|
|
49
60
|
return value;
|
|
50
61
|
},
|
|
51
|
-
|
|
52
|
-
await Promise.all(caches.map((x) => x.reset()));
|
|
62
|
+
async reset() {
|
|
63
|
+
await Promise.all(caches.map(async (x) => x.reset())).catch(error => eventEmitter.emit('error', error));
|
|
53
64
|
},
|
|
54
|
-
|
|
55
|
-
const values =
|
|
65
|
+
async mget(...keys) {
|
|
66
|
+
const values = Array.from({ length: keys.length }).fill(undefined);
|
|
56
67
|
for (const cache of caches) {
|
|
57
|
-
if (values.every(
|
|
68
|
+
if (values.every(x => x !== undefined)) {
|
|
58
69
|
break;
|
|
70
|
+
}
|
|
59
71
|
try {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
72
|
+
// eslint-disable-next-line no-await-in-loop
|
|
73
|
+
const value = await cache.store.mget(...keys);
|
|
74
|
+
for (const [i, v] of value.entries()) {
|
|
75
|
+
if (values[i] === undefined && v !== undefined) {
|
|
63
76
|
values[i] = v;
|
|
64
|
-
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
eventEmitter.emit('error', error);
|
|
65
82
|
}
|
|
66
|
-
catch (e) { }
|
|
67
83
|
}
|
|
68
84
|
return values;
|
|
69
85
|
},
|
|
70
|
-
|
|
71
|
-
await Promise.all(caches.map((cache) => cache.store.mset(
|
|
86
|
+
async mset(arguments_, ttl) {
|
|
87
|
+
await Promise.all(caches.map(async (cache) => cache.store.mset(arguments_, ttl))).catch(error => eventEmitter.emit('error', error));
|
|
72
88
|
},
|
|
73
|
-
|
|
74
|
-
await Promise.all(caches.map((cache) => cache.store.mdel(...keys)))
|
|
89
|
+
async mdel(...keys) {
|
|
90
|
+
await Promise.all(caches.map(async (cache) => cache.store.mdel(...keys)))
|
|
91
|
+
.catch(error => eventEmitter.emit('error', error));
|
|
75
92
|
},
|
|
93
|
+
on: (event, handler) => eventEmitter.on('error', handler),
|
|
76
94
|
};
|
|
77
95
|
}
|
|
78
96
|
exports.multiCaching = multiCaching;
|
package/dist/stores/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from './memory';
|
|
1
|
+
export * from './memory.js';
|
package/dist/stores/index.js
CHANGED
|
@@ -14,5 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
__exportStar(require("./memory"), exports);
|
|
17
|
+
__exportStar(require("./memory.js"), exports);
|
|
18
18
|
//# sourceMappingURL=index.js.map
|
package/dist/stores/memory.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { LRUCache } from 'lru-cache';
|
|
2
|
-
import { Config, Cache, Store } from '../caching';
|
|
3
|
-
type LRU = LRUCache<string, any
|
|
2
|
+
import { type Config, type Cache, type Store } from '../caching.js';
|
|
3
|
+
type LRU = LRUCache<string, any>;
|
|
4
4
|
type Pre = LRUCache.OptionsTTLLimit<string, any, unknown>;
|
|
5
5
|
type Options = Omit<Pre, 'ttlAutopurge'> & Partial<Pick<Pre, 'ttlAutopurge'>>;
|
|
6
6
|
export type MemoryConfig = {
|
|
@@ -9,14 +9,14 @@ export type MemoryConfig = {
|
|
|
9
9
|
shouldCloneBeforeSet?: boolean;
|
|
10
10
|
} & Options & Config;
|
|
11
11
|
export type MemoryStore = Store & {
|
|
12
|
-
get size(): number;
|
|
13
12
|
dump: LRU['dump'];
|
|
14
13
|
load: LRU['load'];
|
|
15
14
|
calculatedSize: LRU['calculatedSize'];
|
|
15
|
+
get size(): number;
|
|
16
16
|
};
|
|
17
17
|
export type MemoryCache = Cache<MemoryStore>;
|
|
18
18
|
/**
|
|
19
19
|
* Wrapper for lru-cache.
|
|
20
20
|
*/
|
|
21
|
-
export declare function memoryStore(
|
|
21
|
+
export declare function memoryStore(arguments_?: MemoryConfig): MemoryStore;
|
|
22
22
|
export {};
|
package/dist/stores/memory.js
CHANGED
|
@@ -15,67 +15,76 @@ function clone(object) {
|
|
|
15
15
|
/**
|
|
16
16
|
* Wrapper for lru-cache.
|
|
17
17
|
*/
|
|
18
|
-
function memoryStore(
|
|
19
|
-
const shouldCloneBeforeSet =
|
|
20
|
-
const isCacheable =
|
|
21
|
-
const
|
|
18
|
+
function memoryStore(arguments_) {
|
|
19
|
+
const shouldCloneBeforeSet = arguments_?.shouldCloneBeforeSet !== false; // Clone by default
|
|
20
|
+
const isCacheable = arguments_?.isCacheable ?? (value => value !== undefined);
|
|
21
|
+
const lruOptions = {
|
|
22
22
|
ttlAutopurge: true,
|
|
23
|
-
...
|
|
24
|
-
max:
|
|
25
|
-
ttl:
|
|
23
|
+
...arguments_,
|
|
24
|
+
max: arguments_?.max ?? 500,
|
|
25
|
+
ttl: arguments_?.ttl === undefined ? 0 : arguments_.ttl,
|
|
26
26
|
};
|
|
27
|
-
const lruCache = new lru_cache_1.LRUCache(
|
|
27
|
+
const lruCache = new lru_cache_1.LRUCache(lruOptions);
|
|
28
28
|
return {
|
|
29
29
|
async del(key) {
|
|
30
30
|
lruCache.delete(key);
|
|
31
31
|
},
|
|
32
32
|
get: async (key) => lruCache.get(key),
|
|
33
33
|
keys: async () => [...lruCache.keys()],
|
|
34
|
-
|
|
35
|
-
async
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
34
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
|
35
|
+
mget: async (...arguments_) => arguments_.map(x => lruCache.get(x)),
|
|
36
|
+
async mset(arguments_, ttl) {
|
|
37
|
+
const opt = { ttl: ttl ?? lruOptions.ttl };
|
|
38
|
+
for (const [key, value] of arguments_) {
|
|
39
|
+
if (!isCacheable(value)) {
|
|
39
40
|
throw new Error(`no cacheable value ${JSON.stringify(value)}`);
|
|
40
|
-
|
|
41
|
+
}
|
|
42
|
+
if (shouldCloneBeforeSet) {
|
|
41
43
|
lruCache.set(key, clone(value), opt);
|
|
42
|
-
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
43
46
|
lruCache.set(key, value, opt);
|
|
47
|
+
}
|
|
44
48
|
}
|
|
45
49
|
},
|
|
46
|
-
async mdel(...
|
|
47
|
-
for (const key of
|
|
50
|
+
async mdel(...arguments_) {
|
|
51
|
+
for (const key of arguments_) {
|
|
48
52
|
lruCache.delete(key);
|
|
53
|
+
}
|
|
49
54
|
},
|
|
50
55
|
async reset() {
|
|
51
56
|
lruCache.clear();
|
|
52
57
|
},
|
|
53
58
|
ttl: async (key) => lruCache.getRemainingTTL(key),
|
|
54
59
|
async set(key, value, opt) {
|
|
55
|
-
if (!isCacheable(value))
|
|
60
|
+
if (!isCacheable(value)) {
|
|
56
61
|
throw new Error(`no cacheable value ${JSON.stringify(value)}`);
|
|
57
|
-
|
|
62
|
+
}
|
|
63
|
+
if (shouldCloneBeforeSet) {
|
|
58
64
|
value = clone(value);
|
|
59
|
-
|
|
65
|
+
}
|
|
66
|
+
const ttl = opt ?? lruOptions.ttl;
|
|
60
67
|
lruCache.set(key, value, { ttl });
|
|
61
68
|
},
|
|
62
69
|
get calculatedSize() {
|
|
63
70
|
return lruCache.calculatedSize;
|
|
64
71
|
},
|
|
65
72
|
/**
|
|
66
|
-
|
|
67
|
-
|
|
73
|
+
* This method is not available in the caching modules.
|
|
74
|
+
*/
|
|
68
75
|
get size() {
|
|
69
76
|
return lruCache.size;
|
|
70
77
|
},
|
|
71
78
|
/**
|
|
72
|
-
|
|
73
|
-
|
|
79
|
+
* This method is not available in the caching modules.
|
|
80
|
+
*/
|
|
74
81
|
dump: () => lruCache.dump(),
|
|
75
82
|
/**
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
load
|
|
83
|
+
* This method is not available in the caching modules.
|
|
84
|
+
*/
|
|
85
|
+
load(...arguments_) {
|
|
86
|
+
lruCache.load(...arguments_);
|
|
87
|
+
},
|
|
79
88
|
};
|
|
80
89
|
}
|
|
81
90
|
exports.memoryStore = memoryStore;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cache-manager",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.5.0",
|
|
4
4
|
"description": "Cache module for Node.js",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -10,20 +10,13 @@
|
|
|
10
10
|
],
|
|
11
11
|
"scripts": {
|
|
12
12
|
"build": "rimraf dist && tsc -p tsconfig.build.json",
|
|
13
|
-
"clean": "rimraf ./dist ./coverage ./node_modules ./package-lock.json ./yarn.lock",
|
|
14
|
-
"test": "vitest run --coverage",
|
|
15
|
-
"
|
|
16
|
-
"prepare": "yarn build",
|
|
17
|
-
"fix": "yarn lint && yarn fmt",
|
|
18
|
-
"check": "yarn lint:check && yarn fmt:check",
|
|
19
|
-
"lint": "eslint --cache --max-warnings 0 --fix '**/*.{ts,mts,js}'",
|
|
20
|
-
"fmt": "prettier --write '**/*.{md,json,yml}'",
|
|
21
|
-
"lint:check": "eslint --cache --max-warnings 0 '**/*.{ts,mts,js}'",
|
|
22
|
-
"fmt:check": "prettier --check '**/*.{md,json,yml}'"
|
|
13
|
+
"clean": "rimraf ./dist ./coverage ./node_modules ./package-lock.json ./yarn.lock ./pnpm-lock.yaml",
|
|
14
|
+
"test": "xo --fix && vitest run --coverage",
|
|
15
|
+
"prepare": "npm run build"
|
|
23
16
|
},
|
|
24
17
|
"repository": {
|
|
25
18
|
"type": "git",
|
|
26
|
-
"url": "https://github.com/node-cache-manager/
|
|
19
|
+
"url": "https://github.com/node-cache-manager/cache-manager.git"
|
|
27
20
|
},
|
|
28
21
|
"keywords": [
|
|
29
22
|
"cache",
|
|
@@ -47,29 +40,29 @@
|
|
|
47
40
|
],
|
|
48
41
|
"license": "MIT",
|
|
49
42
|
"dependencies": {
|
|
43
|
+
"eventemitter3": "^5.0.1",
|
|
50
44
|
"lodash.clonedeep": "^4.5.0",
|
|
51
|
-
"lru-cache": "^10.
|
|
45
|
+
"lru-cache": "^10.2.0",
|
|
52
46
|
"promise-coalesce": "^1.1.2"
|
|
53
47
|
},
|
|
54
48
|
"devDependencies": {
|
|
55
|
-
"@faker-js/faker": "8.
|
|
56
|
-
"@types/lodash.clonedeep": "4.5.9",
|
|
57
|
-
"@types/node": "20.11.
|
|
58
|
-
"@typescript-eslint/eslint-plugin": "
|
|
59
|
-
"@typescript-eslint/parser": "
|
|
60
|
-
"@vitest/coverage-v8": "1.
|
|
61
|
-
"
|
|
62
|
-
"eslint": "8.56.0",
|
|
63
|
-
"eslint-config-prettier": "9.1.0",
|
|
64
|
-
"eslint-plugin-prettier": "5.1.3",
|
|
65
|
-
"lint-staged": "15.2.0",
|
|
66
|
-
"prettier": "3.2.4",
|
|
49
|
+
"@faker-js/faker": "^8.4.1",
|
|
50
|
+
"@types/lodash.clonedeep": "^4.5.9",
|
|
51
|
+
"@types/node": "^20.11.30",
|
|
52
|
+
"@typescript-eslint/eslint-plugin": "^7.4.0",
|
|
53
|
+
"@typescript-eslint/parser": "^7.4.0",
|
|
54
|
+
"@vitest/coverage-v8": "^1.4.0",
|
|
55
|
+
"eslint-config-xo-typescript": "^4.0.0",
|
|
67
56
|
"rimraf": "^5.0.5",
|
|
68
|
-
"typescript": "5.
|
|
69
|
-
"vitest": "1.
|
|
57
|
+
"typescript": "^5.4.3",
|
|
58
|
+
"vitest": "^1.4.0",
|
|
59
|
+
"xo": "^0.58.0"
|
|
70
60
|
},
|
|
71
|
-
"
|
|
72
|
-
"
|
|
73
|
-
"
|
|
61
|
+
"xo": {
|
|
62
|
+
"extends": "xo-typescript",
|
|
63
|
+
"extensions": [
|
|
64
|
+
"ts",
|
|
65
|
+
"tsx"
|
|
66
|
+
]
|
|
74
67
|
}
|
|
75
68
|
}
|
package/READMEv4.md
DELETED
|
@@ -1,542 +0,0 @@
|
|
|
1
|
-
[](http://travis-ci.org/BryanDonovan/node-cache-manager)
|
|
2
|
-
[](https://coveralls.io/r/BryanDonovan/node-cache-manager?branch=master)
|
|
3
|
-
|
|
4
|
-
# node-cache-manager
|
|
5
|
-
|
|
6
|
-
# Flexible NodeJS cache module
|
|
7
|
-
|
|
8
|
-
A cache module for nodejs that allows easy wrapping of functions in cache,
|
|
9
|
-
tiered caches, and a consistent interface.
|
|
10
|
-
|
|
11
|
-
## Features
|
|
12
|
-
|
|
13
|
-
- Easy way to wrap any function in cache.
|
|
14
|
-
- Tiered caches -- data gets stored in each cache and fetched from the highest
|
|
15
|
-
priority cache(s) first.
|
|
16
|
-
- Use any cache you want, as long as it has the same API.
|
|
17
|
-
- 100% test coverage via [mocha](https://github.com/visionmedia/mocha),
|
|
18
|
-
[istanbul](https://github.com/yahoo/istanbul), and [sinon](http://sinonjs.org).
|
|
19
|
-
|
|
20
|
-
## Express.js Example
|
|
21
|
-
|
|
22
|
-
See the [Express.js cache-manager example app](https://github.com/BryanDonovan/node-cache-manager-express-example) to see how to use
|
|
23
|
-
`node-cache-manager` in your applications.
|
|
24
|
-
|
|
25
|
-
## Installation
|
|
26
|
-
|
|
27
|
-
npm install cache-manager
|
|
28
|
-
|
|
29
|
-
## Store Engines
|
|
30
|
-
|
|
31
|
-
- [node-cache-manager-redis](https://github.com/dial-once/node-cache-manager-redis) (uses [sol-redis-pool](https://github.com/joshuah/sol-redis-pool))
|
|
32
|
-
|
|
33
|
-
- [node-cache-manager-redis-store](https://github.com/dabroek/node-cache-manager-redis-store) (uses [node_redis](https://github.com/NodeRedis/node_redis))
|
|
34
|
-
|
|
35
|
-
- [node-cache-manager-ioredis](https://github.com/Tirke/node-cache-manager-ioredis) (uses [ioredis](https://github.com/luin/ioredis))
|
|
36
|
-
|
|
37
|
-
- [node-cache-manager-mongodb](https://github.com/v4l3r10/node-cache-manager-mongodb)
|
|
38
|
-
|
|
39
|
-
- [node-cache-manager-mongoose](https://github.com/disjunction/node-cache-manager-mongoose)
|
|
40
|
-
|
|
41
|
-
- [node-cache-manager-fs-binary](https://github.com/sheershoff/node-cache-manager-fs-binary)
|
|
42
|
-
|
|
43
|
-
- [node-cache-manager-fs-hash](https://github.com/rolandstarke/node-cache-manager-fs-hash)
|
|
44
|
-
|
|
45
|
-
- [node-cache-manager-hazelcast](https://github.com/marudor/node-cache-manager-hazelcast)
|
|
46
|
-
|
|
47
|
-
- [node-cache-manager-memcached-store](https://github.com/theogravity/node-cache-manager-memcached-store)
|
|
48
|
-
|
|
49
|
-
- [node-cache-manager-memory-store](https://github.com/theogravity/node-cache-manager-memory-store)
|
|
50
|
-
|
|
51
|
-
- [node-cache-manager-couchbase](https://github.com/davidepellegatta/node-cache-manager-couchbase)
|
|
52
|
-
|
|
53
|
-
- [node-cache-manager-sqlite](https://github.com/maxpert/node-cache-manager-sqlite)
|
|
54
|
-
|
|
55
|
-
## Overview
|
|
56
|
-
|
|
57
|
-
**First**, it includes a `wrap` function that lets you wrap any function in cache.
|
|
58
|
-
(Note, this was inspired by [node-caching](https://github.com/mape/node-caching).)
|
|
59
|
-
This is probably the feature you're looking for. As an example, where you might have to do this:
|
|
60
|
-
|
|
61
|
-
```javascript
|
|
62
|
-
function getCachedUser(id, cb) {
|
|
63
|
-
memoryCache.get(id, function (err, result) {
|
|
64
|
-
if (err) {
|
|
65
|
-
return cb(err);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
if (result) {
|
|
69
|
-
return cb(null, result);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
getUser(id, function (err, result) {
|
|
73
|
-
if (err) {
|
|
74
|
-
return cb(err);
|
|
75
|
-
}
|
|
76
|
-
memoryCache.set(id, result);
|
|
77
|
-
cb(null, result);
|
|
78
|
-
});
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
... you can instead use the `wrap` function:
|
|
84
|
-
|
|
85
|
-
```javascript
|
|
86
|
-
function getCachedUser(id, cb) {
|
|
87
|
-
memoryCache.wrap(
|
|
88
|
-
id,
|
|
89
|
-
function (cacheCallback) {
|
|
90
|
-
getUser(id, cacheCallback);
|
|
91
|
-
},
|
|
92
|
-
{ ttl: ttl },
|
|
93
|
-
cb,
|
|
94
|
-
);
|
|
95
|
-
}
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
**Second**, node-cache-manager features a built-in memory cache (using [node-lru-cache](https://github.com/isaacs/node-lru-cache)),
|
|
99
|
-
with the standard functions you'd expect in most caches:
|
|
100
|
-
|
|
101
|
-
set(key, val, {ttl: ttl}, cb) // * see note below
|
|
102
|
-
get(key, cb)
|
|
103
|
-
del(key, cb)
|
|
104
|
-
mset(key1, val1, key2, val2, {ttl: ttl}, cb) // set several keys at once
|
|
105
|
-
mget(key1, key2, key3, cb) // get several keys at once
|
|
106
|
-
|
|
107
|
-
// * Note that depending on the underlying store, you may be able to pass the
|
|
108
|
-
// ttl as the third param, like this:
|
|
109
|
-
set(key, val, ttl, cb)
|
|
110
|
-
// ... or pass no ttl at all:
|
|
111
|
-
set(key, val, cb)
|
|
112
|
-
|
|
113
|
-
**Third**, node-cache-manager lets you set up a tiered cache strategy. This may be of
|
|
114
|
-
limited use in most cases, but imagine a scenario where you expect tons of
|
|
115
|
-
traffic, and don't want to hit your primary cache (like Redis) for every request.
|
|
116
|
-
You decide to store the most commonly-requested data in an in-memory cache,
|
|
117
|
-
perhaps with a very short timeout and/or a small data size limit. But you
|
|
118
|
-
still want to store the data in Redis for backup, and for the requests that
|
|
119
|
-
aren't as common as the ones you want to store in memory. This is something
|
|
120
|
-
node-cache-manager handles easily and transparently.
|
|
121
|
-
|
|
122
|
-
**Fourth**, it allows you to get and set multiple keys at once for caching store that support it. This means that when getting muliple keys it will go through the different caches starting from the highest priority one (see multi store below) and merge the values it finds at each level.
|
|
123
|
-
|
|
124
|
-
## Usage Examples
|
|
125
|
-
|
|
126
|
-
See examples below and in the examples directory. See `examples/redis_example` for an example of how to implement a
|
|
127
|
-
Redis cache store with connection pooling.
|
|
128
|
-
|
|
129
|
-
### Single Store
|
|
130
|
-
|
|
131
|
-
```javascript
|
|
132
|
-
var cacheManager = require('cache-manager');
|
|
133
|
-
var memoryCache = cacheManager.caching({
|
|
134
|
-
store: 'memory',
|
|
135
|
-
max: 100,
|
|
136
|
-
ttl: 10 /*seconds*/,
|
|
137
|
-
});
|
|
138
|
-
var ttl = 5;
|
|
139
|
-
// Note: callback is optional in set() and del().
|
|
140
|
-
// Note: memory cache clones values before setting them unless
|
|
141
|
-
// shouldCloneBeforeSet is set to false
|
|
142
|
-
|
|
143
|
-
memoryCache.set('foo', 'bar', { ttl: ttl }, function (err) {
|
|
144
|
-
if (err) {
|
|
145
|
-
throw err;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
memoryCache.get('foo', function (err, result) {
|
|
149
|
-
console.log(result);
|
|
150
|
-
// >> 'bar'
|
|
151
|
-
memoryCache.del('foo', function (err) {});
|
|
152
|
-
});
|
|
153
|
-
});
|
|
154
|
-
|
|
155
|
-
function getUser(id, cb) {
|
|
156
|
-
setTimeout(function () {
|
|
157
|
-
console.log('Returning user from slow database.');
|
|
158
|
-
cb(null, { id: id, name: 'Bob' });
|
|
159
|
-
}, 100);
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
var userId = 123;
|
|
163
|
-
var key = 'user_' + userId;
|
|
164
|
-
|
|
165
|
-
// Note: ttl is optional in wrap()
|
|
166
|
-
memoryCache.wrap(
|
|
167
|
-
key,
|
|
168
|
-
function (cb) {
|
|
169
|
-
getUser(userId, cb);
|
|
170
|
-
},
|
|
171
|
-
{ ttl: ttl },
|
|
172
|
-
function (err, user) {
|
|
173
|
-
console.log(user);
|
|
174
|
-
|
|
175
|
-
// Second time fetches user from memoryCache
|
|
176
|
-
memoryCache.wrap(
|
|
177
|
-
key,
|
|
178
|
-
function (cb) {
|
|
179
|
-
getUser(userId, cb);
|
|
180
|
-
},
|
|
181
|
-
function (err, user) {
|
|
182
|
-
console.log(user);
|
|
183
|
-
},
|
|
184
|
-
);
|
|
185
|
-
},
|
|
186
|
-
);
|
|
187
|
-
|
|
188
|
-
// Outputs:
|
|
189
|
-
// Returning user from slow database.
|
|
190
|
-
// { id: 123, name: 'Bob' }
|
|
191
|
-
// { id: 123, name: 'Bob' }
|
|
192
|
-
```
|
|
193
|
-
|
|
194
|
-
The `ttl` can also be computed dynamically by passing in a function. E.g.,
|
|
195
|
-
|
|
196
|
-
```javascript
|
|
197
|
-
var opts = {
|
|
198
|
-
ttl: function(user) {
|
|
199
|
-
if (user.id === 1) {
|
|
200
|
-
return 0.1;
|
|
201
|
-
} else {
|
|
202
|
-
return 0.5;
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
};
|
|
206
|
-
|
|
207
|
-
memoryCache.wrap(key, function(cb) {
|
|
208
|
-
getUser(userId, cb);
|
|
209
|
-
}, opts, function(err, user) {
|
|
210
|
-
console.log(user);
|
|
211
|
-
}
|
|
212
|
-
```
|
|
213
|
-
|
|
214
|
-
You can get several keys at once. Note that this will return whatever records it
|
|
215
|
-
finds in the cache and it is up to the user to check the results against the
|
|
216
|
-
supplied keys and make any calls to the underlying data store to fill in
|
|
217
|
-
missing records. In practice, this should not be much of a concern if you are
|
|
218
|
-
only using the `wrap` function to set these records in cache.
|
|
219
|
-
|
|
220
|
-
Side note: Ideally the `wrap` function would get what it can from the cache and fill in
|
|
221
|
-
the missing records from the data store, but I can't think of a way to do this
|
|
222
|
-
that is generic to all situations. Another option is to only return the data
|
|
223
|
-
from the cache if all records are found, but this woul break multi-caching.
|
|
224
|
-
|
|
225
|
-
See unit tests in `caching.unit.js` for more information.
|
|
226
|
-
|
|
227
|
-
Example:
|
|
228
|
-
|
|
229
|
-
```js
|
|
230
|
-
var key1 = 'user_1';
|
|
231
|
-
var key2 = 'user_1';
|
|
232
|
-
|
|
233
|
-
memoryCache.wrap(
|
|
234
|
-
key1,
|
|
235
|
-
key2,
|
|
236
|
-
function (cb) {
|
|
237
|
-
getManyUser([key1, key2], cb);
|
|
238
|
-
},
|
|
239
|
-
function (err, users) {
|
|
240
|
-
console.log(users[0]);
|
|
241
|
-
console.log(users[1]);
|
|
242
|
-
},
|
|
243
|
-
);
|
|
244
|
-
```
|
|
245
|
-
|
|
246
|
-
#### Example setting/getting several keys with mset() and mget()
|
|
247
|
-
|
|
248
|
-
```js
|
|
249
|
-
memoryCache.mset('foo', 'bar', 'foo2', 'bar2', { ttl: ttl }, function (err) {
|
|
250
|
-
if (err) {
|
|
251
|
-
throw err;
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
memoryCache.mget('foo', 'foo2', function (err, result) {
|
|
255
|
-
console.log(result);
|
|
256
|
-
// >> ['bar', 'bar2']
|
|
257
|
-
|
|
258
|
-
// Delete keys with del() passing arguments...
|
|
259
|
-
memoryCache.del('foo', 'foo2', function (err) {});
|
|
260
|
-
|
|
261
|
-
// ...passing an Array of keys
|
|
262
|
-
memoryCache.del(['foo', 'foo2'], function (err) {});
|
|
263
|
-
});
|
|
264
|
-
});
|
|
265
|
-
```
|
|
266
|
-
|
|
267
|
-
#### Example Using Promises
|
|
268
|
-
|
|
269
|
-
```javascript
|
|
270
|
-
memoryCache
|
|
271
|
-
.wrap(key, function () {
|
|
272
|
-
return getUserPromise(userId);
|
|
273
|
-
})
|
|
274
|
-
.then(function (user) {
|
|
275
|
-
console.log('User:', user);
|
|
276
|
-
});
|
|
277
|
-
```
|
|
278
|
-
|
|
279
|
-
If you are using a Node version that does not include native promises, you can
|
|
280
|
-
specify your promise dependency in the options passed to the cache module.
|
|
281
|
-
E.g.,
|
|
282
|
-
|
|
283
|
-
```javascript
|
|
284
|
-
var Promise = require('es6-promise').Promise;
|
|
285
|
-
cache = caching({ store: store, promiseDependency: Promise });
|
|
286
|
-
```
|
|
287
|
-
|
|
288
|
-
#### Example Using async/await
|
|
289
|
-
|
|
290
|
-
```javascript
|
|
291
|
-
try {
|
|
292
|
-
let user = await memoryCache.wrap(key, function () {
|
|
293
|
-
return getUserPromise(userId);
|
|
294
|
-
});
|
|
295
|
-
} catch (err) {
|
|
296
|
-
// error handling
|
|
297
|
-
}
|
|
298
|
-
```
|
|
299
|
-
|
|
300
|
-
Hint: should wrap `await` call with `try` - `catch` to handle `promise` error.
|
|
301
|
-
|
|
302
|
-
#### Example Express App Usage
|
|
303
|
-
|
|
304
|
-
(Also see the [Express.js cache-manager example app](https://github.com/BryanDonovan/node-cache-manager-express-example)).
|
|
305
|
-
|
|
306
|
-
```javascript
|
|
307
|
-
function respond(res, err, data) {
|
|
308
|
-
if (err) {
|
|
309
|
-
res.json(500, err);
|
|
310
|
-
} else {
|
|
311
|
-
res.json(200, data);
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
app.get('/foo/bar', function (req, res) {
|
|
316
|
-
var cacheKey = 'foo-bar:' + JSON.stringify(req.query);
|
|
317
|
-
var ttl = 10;
|
|
318
|
-
memoryCache.wrap(
|
|
319
|
-
cacheKey,
|
|
320
|
-
function (cacheCallback) {
|
|
321
|
-
DB.find(req.query, cacheCallback);
|
|
322
|
-
},
|
|
323
|
-
{ ttl: ttl },
|
|
324
|
-
function (err, result) {
|
|
325
|
-
respond(res, err, result);
|
|
326
|
-
},
|
|
327
|
-
);
|
|
328
|
-
});
|
|
329
|
-
```
|
|
330
|
-
|
|
331
|
-
#### Custom Stores
|
|
332
|
-
|
|
333
|
-
You can use your own custom store by creating one with the same API as the
|
|
334
|
-
built-in memory stores (such as a redis or memcached store). To use your own store just pass
|
|
335
|
-
in an instance of it.
|
|
336
|
-
|
|
337
|
-
E.g.,
|
|
338
|
-
|
|
339
|
-
```javascript
|
|
340
|
-
var myStore = require('your-homemade-store');
|
|
341
|
-
var cache = cacheManager.caching({ store: myStore });
|
|
342
|
-
```
|
|
343
|
-
|
|
344
|
-
### Multi-Store
|
|
345
|
-
|
|
346
|
-
```javascript
|
|
347
|
-
var multiCache = cacheManager.multiCaching([memoryCache, someOtherCache]);
|
|
348
|
-
userId2 = 456;
|
|
349
|
-
key2 = 'user_' + userId;
|
|
350
|
-
ttl = 5;
|
|
351
|
-
|
|
352
|
-
// Sets in all caches.
|
|
353
|
-
// The "ttl" option can also be a function (see example below)
|
|
354
|
-
multiCache.set('foo2', 'bar2', { ttl: ttl }, function (err) {
|
|
355
|
-
if (err) {
|
|
356
|
-
throw err;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
// Fetches from highest priority cache that has the key.
|
|
360
|
-
multiCache.get('foo2', function (err, result) {
|
|
361
|
-
console.log(result);
|
|
362
|
-
// >> 'bar2'
|
|
363
|
-
|
|
364
|
-
// Delete from all caches
|
|
365
|
-
multiCache.del('foo2');
|
|
366
|
-
});
|
|
367
|
-
});
|
|
368
|
-
|
|
369
|
-
// Set the ttl value by context depending on the store.
|
|
370
|
-
function getTTL(data, store) {
|
|
371
|
-
if (store === 'redis') {
|
|
372
|
-
return 6000;
|
|
373
|
-
}
|
|
374
|
-
return 3000;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
// Sets multiple keys in all caches.
|
|
378
|
-
// You can pass as many key,value pair as you want
|
|
379
|
-
multiCache.mset(
|
|
380
|
-
'key',
|
|
381
|
-
'value',
|
|
382
|
-
'key2',
|
|
383
|
-
'value2',
|
|
384
|
-
{ ttl: getTTL },
|
|
385
|
-
function (err) {
|
|
386
|
-
if (err) {
|
|
387
|
-
throw err;
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
// mget() fetches from highest priority cache.
|
|
391
|
-
// If the first cache does not return all the keys,
|
|
392
|
-
// the next cache is fetched with the keys that were not found.
|
|
393
|
-
// This is done recursively until either:
|
|
394
|
-
// - all have been found
|
|
395
|
-
// - all caches has been fetched
|
|
396
|
-
multiCache.mget('key', 'key2', function (err, result) {
|
|
397
|
-
console.log(result[0]);
|
|
398
|
-
console.log(result[1]);
|
|
399
|
-
// >> 'bar2'
|
|
400
|
-
// >> 'bar3'
|
|
401
|
-
|
|
402
|
-
// Delete from all caches
|
|
403
|
-
multiCache.del('key', 'key2');
|
|
404
|
-
// ...or with an Array
|
|
405
|
-
multiCache.del(['key', 'key2']);
|
|
406
|
-
});
|
|
407
|
-
},
|
|
408
|
-
);
|
|
409
|
-
|
|
410
|
-
// Note: options with ttl are optional in wrap()
|
|
411
|
-
multiCache.wrap(
|
|
412
|
-
key2,
|
|
413
|
-
function (cb) {
|
|
414
|
-
getUser(userId2, cb);
|
|
415
|
-
},
|
|
416
|
-
{ ttl: ttl },
|
|
417
|
-
function (err, user) {
|
|
418
|
-
console.log(user);
|
|
419
|
-
|
|
420
|
-
// Second time fetches user from memoryCache, since it's highest priority.
|
|
421
|
-
// If the data expires in the memory cache, the next fetch would pull it from
|
|
422
|
-
// the 'someOtherCache', and set the data in memory again.
|
|
423
|
-
multiCache.wrap(
|
|
424
|
-
key2,
|
|
425
|
-
function (cb) {
|
|
426
|
-
getUser(userId2, cb);
|
|
427
|
-
},
|
|
428
|
-
function (err, user) {
|
|
429
|
-
console.log(user);
|
|
430
|
-
},
|
|
431
|
-
);
|
|
432
|
-
},
|
|
433
|
-
);
|
|
434
|
-
|
|
435
|
-
// Multiple keys
|
|
436
|
-
multiCache.wrap(
|
|
437
|
-
'key1',
|
|
438
|
-
'key2',
|
|
439
|
-
function (cb) {
|
|
440
|
-
getManyUser(['key1', 'key2'], cb);
|
|
441
|
-
},
|
|
442
|
-
{ ttl: ttl },
|
|
443
|
-
function (err, users) {
|
|
444
|
-
console.log(users[0]);
|
|
445
|
-
console.log(users[1]);
|
|
446
|
-
},
|
|
447
|
-
);
|
|
448
|
-
```
|
|
449
|
-
|
|
450
|
-
### Specifying What to Cache in `wrap` Function
|
|
451
|
-
|
|
452
|
-
Both the `caching` and `multicaching` modules allow you to pass in a callback function named
|
|
453
|
-
`isCacheableValue` which is called by the `wrap` function with every value returned from cache or from the wrapped function.
|
|
454
|
-
This lets you specify which values should and should not be cached by `wrap`. If the function returns true, it will be
|
|
455
|
-
stored in cache. By default the caches cache everything except `undefined`.
|
|
456
|
-
|
|
457
|
-
NOTE: The `set` functions in `caching` and `multicaching` do _not_ use `isCacheableValue`.
|
|
458
|
-
|
|
459
|
-
For example, if you don't want to cache `false` and `null`, you can pass in a function like this:
|
|
460
|
-
|
|
461
|
-
```javascript
|
|
462
|
-
var isCacheableValue = function (value) {
|
|
463
|
-
return value !== null && value !== false && value !== undefined;
|
|
464
|
-
};
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
Then pass it to `caching` like this:
|
|
468
|
-
|
|
469
|
-
```javascript
|
|
470
|
-
var memoryCache = cacheManager.caching({
|
|
471
|
-
store: 'memory',
|
|
472
|
-
isCacheableValue: isCacheableValue,
|
|
473
|
-
});
|
|
474
|
-
```
|
|
475
|
-
|
|
476
|
-
And pass it to `multicaching` like this:
|
|
477
|
-
|
|
478
|
-
```javascript
|
|
479
|
-
var multiCache = cacheManager.multiCaching([memoryCache, someOtherCache], {
|
|
480
|
-
isCacheableValue: isCacheableValue,
|
|
481
|
-
});
|
|
482
|
-
```
|
|
483
|
-
|
|
484
|
-
### Refresh cache keys in background
|
|
485
|
-
|
|
486
|
-
Both the `caching` and `multicaching` modules support a mechanism to refresh expiring cache keys in background when using `wrap` function.
|
|
487
|
-
This is done by adding a `refreshThreshold` attribute while creating the caching store.
|
|
488
|
-
|
|
489
|
-
If `refreshThreshold` is set and if the `ttl` method is available for the used store, after retrieving a value from cache TTL will be checked.
|
|
490
|
-
If the remaining TTL is less than `refreshThreshold`, the system will spawn a background worker to update the value, following same rules as standard fetching. In the meantime, the system will return the old value until expiration.
|
|
491
|
-
|
|
492
|
-
In case of multicaching, the store that will be used for refresh is the one where the key will be found first (highest priority). The value will then be set in all the stores.
|
|
493
|
-
|
|
494
|
-
NOTES:
|
|
495
|
-
|
|
496
|
-
- In case of multicaching, the store that will be checked for refresh is the one where the key will be found first (highest priority).
|
|
497
|
-
- 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.
|
|
498
|
-
- The background refresh mechanism currently does not support providing multiple keys to `wrap` function.
|
|
499
|
-
- The caching store needs to provide the `ttl` method.
|
|
500
|
-
|
|
501
|
-
For example, pass the refreshThreshold to `caching` like this:
|
|
502
|
-
|
|
503
|
-
```javascript
|
|
504
|
-
var redisStore = require('cache-manager-ioredis');
|
|
505
|
-
|
|
506
|
-
var redisCache = cacheManager.caching({
|
|
507
|
-
store: redisStore,
|
|
508
|
-
refreshThreshold: 3,
|
|
509
|
-
isCacheableValue: isCacheableValue,
|
|
510
|
-
});
|
|
511
|
-
```
|
|
512
|
-
|
|
513
|
-
When a value will be retrieved from Redis with a remaining TTL < 3sec, the value will be updated in background.
|
|
514
|
-
|
|
515
|
-
### Development environment
|
|
516
|
-
|
|
517
|
-
You may disable real caching but still get all the callback functionality working by setting `none` store.
|
|
518
|
-
|
|
519
|
-
## Docs
|
|
520
|
-
|
|
521
|
-
To generate JSDOC 3 documentation:
|
|
522
|
-
|
|
523
|
-
make docs
|
|
524
|
-
|
|
525
|
-
## Tests
|
|
526
|
-
|
|
527
|
-
To run tests, first run:
|
|
528
|
-
|
|
529
|
-
npm install -d
|
|
530
|
-
|
|
531
|
-
Run the tests and JShint:
|
|
532
|
-
|
|
533
|
-
make
|
|
534
|
-
|
|
535
|
-
## Contribute
|
|
536
|
-
|
|
537
|
-
If you would like to contribute to the project, please fork it and send us a pull request. Please add tests
|
|
538
|
-
for any new features or bug fixes. Also run `make` before submitting the pull request.
|
|
539
|
-
|
|
540
|
-
## License
|
|
541
|
-
|
|
542
|
-
node-cache-manager is licensed under the MIT license.
|