cache-manager 5.3.0 → 5.3.2

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
@@ -84,6 +84,32 @@ You can use your own custom store by creating one with the same API as the built
84
84
  - [Example Custom Store redis](https://github.com/node-cache-manager/node-cache-manager-redis-yet)
85
85
  - [Example Custom Store ioredis](https://github.com/node-cache-manager/node-cache-manager-ioredis-yet)
86
86
 
87
+ #### Create single cache store synchronously
88
+
89
+ As `caching()` requires async functionality to resolve some stores, this is not well-suited to use for default function/constructor parameters etc.
90
+
91
+ If you need to create a cache store synchronously, you can instead use `createCache()`:
92
+
93
+ ```typescript
94
+ import { createCache, memoryStore } from 'node-cache-manager';
95
+
96
+ // Create memory cache synchronously
97
+ const memoryCache = createCache(memoryStore(), {
98
+ max: 100,
99
+ ttl: 10 * 1000 /*milliseconds*/,
100
+ });
101
+
102
+ // Default parameter in function
103
+ function myService(cache = createCache(memoryStore())) {}
104
+
105
+ // Default parameter in class constructor
106
+ const DEFAULT_CACHE = createCache(memoryStore(), { ttl: 60 * 1000 });
107
+ // ...
108
+ class MyService {
109
+ constructor(private cache = DEFAULT_CACHE) {}
110
+ }
111
+ ```
112
+
87
113
  ### Multi-Store
88
114
 
89
115
  ```typescript
@@ -0,0 +1,41 @@
1
+ import { MemoryCache, MemoryConfig, MemoryStore } from './stores';
2
+ export type Config = {
3
+ ttl?: Milliseconds;
4
+ refreshThreshold?: Milliseconds;
5
+ isCacheable?: (val: unknown) => boolean;
6
+ };
7
+ export type Milliseconds = number;
8
+ /**
9
+ * @deprecated will remove after 5.2.0. Use Milliseconds instead
10
+ */
11
+ export type Ttl = Milliseconds;
12
+ export type Store = {
13
+ get<T>(key: string): Promise<T | undefined>;
14
+ set<T>(key: string, data: T, ttl?: Milliseconds): Promise<void>;
15
+ del(key: string): Promise<void>;
16
+ reset(): Promise<void>;
17
+ mset(args: [string, unknown][], ttl?: Milliseconds): Promise<void>;
18
+ mget(...args: string[]): Promise<unknown[]>;
19
+ mdel(...args: string[]): Promise<void>;
20
+ keys(pattern?: string): Promise<string[]>;
21
+ ttl(key: string): Promise<number>;
22
+ };
23
+ export type StoreConfig = Config;
24
+ export type FactoryConfig<T> = T & Config;
25
+ export type FactoryStore<S extends Store, T extends object = never> = (config?: FactoryConfig<T>) => S | Promise<S>;
26
+ export type Stores<S extends Store, T extends object> = 'memory' | Store | FactoryStore<S, T>;
27
+ export type CachingConfig<T> = MemoryConfig | StoreConfig | FactoryConfig<T>;
28
+ export type WrapTTL<T> = Milliseconds | ((v: T) => Milliseconds);
29
+ export type Cache<S extends Store = Store> = {
30
+ set: (key: string, value: unknown, ttl?: Milliseconds) => Promise<void>;
31
+ get: <T>(key: string) => Promise<T | undefined>;
32
+ del: (key: string) => Promise<void>;
33
+ reset: () => Promise<void>;
34
+ wrap<T>(key: string, fn: () => Promise<T>, ttl?: WrapTTL<T>): Promise<T>;
35
+ store: S;
36
+ };
37
+ export declare function caching(name: 'memory', args?: MemoryConfig): Promise<MemoryCache>;
38
+ export declare function caching<S extends Store>(store: S): Promise<Cache<S>>;
39
+ export declare function caching<S extends Store, T extends object = never>(factory: FactoryStore<S, T>, args?: FactoryConfig<T>): Promise<Cache<S>>;
40
+ export declare function createCache(store: MemoryStore, args?: MemoryConfig): MemoryCache;
41
+ export declare function createCache(store: Store, args?: Config): Cache<Store>;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createCache = exports.caching = void 0;
4
+ const promise_coalesce_1 = require("promise-coalesce");
5
+ const stores_1 = require("./stores");
6
+ /**
7
+ * Generic caching interface that wraps any caching library with a compatible interface.
8
+ */
9
+ async function caching(factory, args) {
10
+ if (factory === 'memory') {
11
+ const store = (0, stores_1.memoryStore)(args);
12
+ return createCache(store, args);
13
+ }
14
+ if (typeof factory === 'function') {
15
+ const store = await factory(args);
16
+ return createCache(store, args);
17
+ }
18
+ const store = factory;
19
+ return createCache(store, args);
20
+ }
21
+ exports.caching = caching;
22
+ /**
23
+ * Create cache instance by store (non-async).
24
+ */
25
+ function createCache(store, args) {
26
+ return {
27
+ /**
28
+ * Wraps a function in cache. I.e., the first time the function is run,
29
+ * its results are stored in cache so subsequent calls retrieve from cache
30
+ * instead of calling the function.
31
+
32
+ * @example
33
+ * const result = await cache.wrap('key', () => Promise.resolve(1));
34
+ *
35
+ */
36
+ wrap: async (key, fn, ttl) => {
37
+ return (0, promise_coalesce_1.coalesceAsync)(key, async () => {
38
+ const value = await store.get(key);
39
+ if (value === undefined) {
40
+ const result = await fn();
41
+ const cacheTTL = typeof ttl === 'function' ? ttl(result) : ttl;
42
+ await store.set(key, result, cacheTTL);
43
+ return result;
44
+ }
45
+ else if (args?.refreshThreshold) {
46
+ const cacheTTL = typeof ttl === 'function' ? ttl(value) : ttl;
47
+ const remainingTtl = await store.ttl(key);
48
+ if (remainingTtl !== -1 && remainingTtl < args.refreshThreshold) {
49
+ (0, promise_coalesce_1.coalesceAsync)(`+++${key}`, fn).then((result) => store.set(key, result, cacheTTL));
50
+ }
51
+ }
52
+ return value;
53
+ });
54
+ },
55
+ store: store,
56
+ del: (key) => store.del(key),
57
+ get: (key) => store.get(key),
58
+ set: (key, value, ttl) => store.set(key, value, ttl),
59
+ reset: () => store.reset(),
60
+ };
61
+ }
62
+ exports.createCache = createCache;
63
+ //# sourceMappingURL=caching.js.map
@@ -0,0 +1,3 @@
1
+ export * from './caching';
2
+ export * from './multi-caching';
3
+ export * from './stores';
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./caching"), exports);
18
+ __exportStar(require("./multi-caching"), exports);
19
+ __exportStar(require("./stores"), exports);
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ import { Cache } from './caching';
2
+ export type MultiCache = Omit<Cache, 'store'> & Pick<Cache['store'], 'mset' | 'mget' | 'mdel'>;
3
+ /**
4
+ * Module that lets you specify a hierarchy of caches.
5
+ */
6
+ export declare function multiCaching<Caches extends Cache[]>(caches: Caches): MultiCache;
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.multiCaching = void 0;
4
+ /**
5
+ * Module that lets you specify a hierarchy of caches.
6
+ */
7
+ function multiCaching(caches) {
8
+ const get = async (key) => {
9
+ for (const cache of caches) {
10
+ try {
11
+ const val = await cache.get(key);
12
+ if (val !== undefined)
13
+ return val;
14
+ }
15
+ catch (e) { }
16
+ }
17
+ };
18
+ const set = async (key, data, ttl) => {
19
+ await Promise.all(caches.map((cache) => cache.set(key, data, ttl)));
20
+ };
21
+ return {
22
+ get,
23
+ set,
24
+ del: async (key) => {
25
+ await Promise.all(caches.map((cache) => cache.del(key)));
26
+ },
27
+ async wrap(key, fn, ttl) {
28
+ let value;
29
+ let i = 0;
30
+ for (; i < caches.length; i++) {
31
+ try {
32
+ value = await caches[i].get(key);
33
+ if (value !== undefined)
34
+ break;
35
+ }
36
+ catch (e) { }
37
+ }
38
+ if (value === undefined) {
39
+ const result = await fn();
40
+ const cacheTTL = typeof ttl === 'function' ? ttl(result) : ttl;
41
+ await set(key, result, cacheTTL);
42
+ return result;
43
+ }
44
+ else {
45
+ const cacheTTL = typeof ttl === 'function' ? ttl(value) : ttl;
46
+ Promise.all(caches.slice(0, i).map((cache) => cache.set(key, value, cacheTTL))).then();
47
+ caches[i].wrap(key, fn, ttl).then(); // call wrap for store for internal refreshThreshold logic, see: src/caching.ts caching.wrap
48
+ }
49
+ return value;
50
+ },
51
+ reset: async () => {
52
+ await Promise.all(caches.map((x) => x.reset()));
53
+ },
54
+ mget: async (...keys) => {
55
+ const values = new Array(keys.length).fill(undefined);
56
+ for (const cache of caches) {
57
+ if (values.every((x) => x !== undefined))
58
+ break;
59
+ try {
60
+ const val = await cache.store.mget(...keys);
61
+ val.forEach((v, i) => {
62
+ if (values[i] === undefined && v !== undefined)
63
+ values[i] = v;
64
+ });
65
+ }
66
+ catch (e) { }
67
+ }
68
+ return values;
69
+ },
70
+ mset: async (args, ttl) => {
71
+ await Promise.all(caches.map((cache) => cache.store.mset(args, ttl)));
72
+ },
73
+ mdel: async (...keys) => {
74
+ await Promise.all(caches.map((cache) => cache.store.mdel(...keys)));
75
+ },
76
+ };
77
+ }
78
+ exports.multiCaching = multiCaching;
79
+ //# sourceMappingURL=multi-caching.js.map
@@ -0,0 +1 @@
1
+ export * from './memory';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./memory"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,22 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ import { Config, Cache, Store } from '../caching';
3
+ type LRU = LRUCache<string, any, unknown>;
4
+ type Pre = LRUCache.OptionsTTLLimit<string, any, unknown>;
5
+ type Options = Omit<Pre, 'ttlAutopurge'> & Partial<Pick<Pre, 'ttlAutopurge'>>;
6
+ export type MemoryConfig = {
7
+ max?: number;
8
+ sizeCalculation?: (value: unknown, key: string) => number;
9
+ shouldCloneBeforeSet?: boolean;
10
+ } & Options & Config;
11
+ export type MemoryStore = Store & {
12
+ get size(): number;
13
+ dump: LRU['dump'];
14
+ load: LRU['load'];
15
+ calculatedSize: LRU['calculatedSize'];
16
+ };
17
+ export type MemoryCache = Cache<MemoryStore>;
18
+ /**
19
+ * Wrapper for lru-cache.
20
+ */
21
+ export declare function memoryStore(args?: MemoryConfig): MemoryStore;
22
+ export {};
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.memoryStore = void 0;
7
+ const lru_cache_1 = require("lru-cache");
8
+ const lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep"));
9
+ function clone(object) {
10
+ if (typeof object === 'object' && object !== null) {
11
+ return (0, lodash_clonedeep_1.default)(object);
12
+ }
13
+ return object;
14
+ }
15
+ /**
16
+ * Wrapper for lru-cache.
17
+ */
18
+ function memoryStore(args) {
19
+ const shouldCloneBeforeSet = args?.shouldCloneBeforeSet !== false; // clone by default
20
+ const isCacheable = args?.isCacheable ?? ((val) => val !== undefined);
21
+ const lruOpts = {
22
+ ttlAutopurge: true,
23
+ ...args,
24
+ max: args?.max || 500,
25
+ ttl: args?.ttl !== undefined ? args.ttl : 0,
26
+ };
27
+ const lruCache = new lru_cache_1.LRUCache(lruOpts);
28
+ return {
29
+ async del(key) {
30
+ lruCache.delete(key);
31
+ },
32
+ get: async (key) => lruCache.get(key),
33
+ keys: async () => [...lruCache.keys()],
34
+ mget: async (...args) => args.map((x) => lruCache.get(x)),
35
+ async mset(args, ttl) {
36
+ const opt = { ttl: ttl !== undefined ? ttl : lruOpts.ttl };
37
+ for (const [key, value] of args) {
38
+ if (!isCacheable(value))
39
+ throw new Error(`no cacheable value ${JSON.stringify(value)}`);
40
+ if (shouldCloneBeforeSet)
41
+ lruCache.set(key, clone(value), opt);
42
+ else
43
+ lruCache.set(key, value, opt);
44
+ }
45
+ },
46
+ async mdel(...args) {
47
+ for (const key of args)
48
+ lruCache.delete(key);
49
+ },
50
+ async reset() {
51
+ lruCache.clear();
52
+ },
53
+ ttl: async (key) => lruCache.getRemainingTTL(key),
54
+ async set(key, value, opt) {
55
+ if (!isCacheable(value))
56
+ throw new Error(`no cacheable value ${JSON.stringify(value)}`);
57
+ if (shouldCloneBeforeSet)
58
+ value = clone(value);
59
+ const ttl = opt !== undefined ? opt : lruOpts.ttl;
60
+ lruCache.set(key, value, { ttl });
61
+ },
62
+ get calculatedSize() {
63
+ return lruCache.calculatedSize;
64
+ },
65
+ /**
66
+ * This method is not available in the caching modules.
67
+ */
68
+ get size() {
69
+ return lruCache.size;
70
+ },
71
+ /**
72
+ * This method is not available in the caching modules.
73
+ */
74
+ dump: () => lruCache.dump(),
75
+ /**
76
+ * This method is not available in the caching modules.
77
+ */
78
+ load: (...args) => lruCache.load(...args),
79
+ };
80
+ }
81
+ exports.memoryStore = memoryStore;
82
+ //# sourceMappingURL=memory.js.map
package/package.json CHANGED
@@ -1,16 +1,19 @@
1
1
  {
2
2
  "name": "cache-manager",
3
- "version": "5.3.0",
3
+ "version": "5.3.2",
4
4
  "description": "Cache module for Node.js",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "files": [
8
- "dist"
8
+ "dist/**/*.js",
9
+ "dist/**/*.d.ts"
9
10
  ],
10
11
  "scripts": {
11
- "build": "rm -rf dist && tsc -p tsconfig.build.json",
12
+ "build": "rimraf dist && tsc -p tsconfig.build.json",
13
+ "clean": "rimraf ./dist ./coverage ./node_modules ./package-lock.json ./yarn.lock",
12
14
  "test": "vitest run --coverage",
13
15
  "release": "yarn check && yarn test -- --run && yarn build",
16
+ "prepare": "yarn build",
14
17
  "fix": "yarn lint && yarn fmt",
15
18
  "check": "yarn lint:check && yarn fmt:check",
16
19
  "lint": "eslint --cache --max-warnings 0 --fix '**/*.{ts,mts,js}'",
@@ -45,24 +48,25 @@
45
48
  "license": "MIT",
46
49
  "dependencies": {
47
50
  "lodash.clonedeep": "^4.5.0",
48
- "lru-cache": "^10.0.2",
49
- "promise-coalesce": "^1.1.1"
51
+ "lru-cache": "^10.1.0",
52
+ "promise-coalesce": "^1.1.2"
50
53
  },
51
54
  "devDependencies": {
52
55
  "@faker-js/faker": "8.3.1",
53
56
  "@types/lodash.clonedeep": "4.5.9",
54
- "@types/node": "20.9.0",
55
- "@typescript-eslint/eslint-plugin": "6.11.0",
56
- "@typescript-eslint/parser": "6.11.0",
57
- "@vitest/coverage-v8": "0.34.6",
57
+ "@types/node": "20.10.5",
58
+ "@typescript-eslint/eslint-plugin": "6.15.0",
59
+ "@typescript-eslint/parser": "6.15.0",
60
+ "@vitest/coverage-v8": "1.1.0",
58
61
  "dotenv-cli": "7.3.0",
59
- "eslint": "8.53.0",
60
- "eslint-config-prettier": "9.0.0",
62
+ "eslint": "8.56.0",
63
+ "eslint-config-prettier": "9.1.0",
61
64
  "eslint-plugin-prettier": "5.0.1",
62
- "lint-staged": "15.1.0",
63
- "prettier": "3.1.0",
64
- "typescript": "5.2.2",
65
- "vitest": "0.34.6"
65
+ "lint-staged": "15.2.0",
66
+ "prettier": "3.1.1",
67
+ "rimraf": "^5.0.5",
68
+ "typescript": "5.3.3",
69
+ "vitest": "1.1.0"
66
70
  },
67
71
  "lint-staged": {
68
72
  "*.{ts,js,mts,mjs}": "eslint --cache --fix",