@tsed/ioredis 8.0.0 → 8.0.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.
@@ -4,9 +4,9 @@ import { Logger } from "@tsed/logger";
4
4
  import ioredis from "ioredis";
5
5
  import { ioRedisStore } from "../domain/IORedisStore.js";
6
6
  export const IOREDIS_CONNECTIONS = Symbol.for("ioredis:connections");
7
- export function registerConnectionProvider({ token, name = "default" }) {
7
+ export function registerConnectionProvider({ token, provide, name = "default" }) {
8
8
  registerProvider({
9
- token,
9
+ token: provide || token,
10
10
  type: IOREDIS_CONNECTIONS,
11
11
  connectionName: name,
12
12
  deps: [Configuration, Logger],
@@ -1 +1 @@
1
- {"version":3,"file":"registerConnectionProvider.js","sourceRoot":"","sources":["../../../src/utils/registerConnectionProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,YAAY,CAAC;AACpC,OAAO,EAAC,aAAa,EAAE,gBAAgB,EAAgB,MAAM,UAAU,CAAC;AACxE,OAAO,EAAC,MAAM,EAAC,MAAM,cAAc,CAAC;AAEpC,OAAO,OAAO,MAAM,SAAS,CAAC;AAG9B,OAAO,EAAC,YAAY,EAAC,MAAM,2BAA2B,CAAC;AAOvD,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAGrE,MAAM,UAAU,0BAA0B,CAAC,EAAC,KAAK,EAAE,IAAI,GAAG,SAAS,EAAgC;IACjG,gBAAgB,CAAC;QACf,KAAK;QACL,IAAI,EAAE,mBAAmB;QACzB,cAAc,EAAE,IAAI;QACpB,IAAI,EAAE,CAAC,aAAa,EAAE,MAAM,CAAC;QAC7B,KAAK,CAAC,eAAe,CAAC,aAA4B,EAAE,MAAc;YAChE,MAAM,KAAK,GAAG,aAAa,CAAC,GAAG,CAAyB,SAAS,EAAE,EAAE,CAAC,CAAC;YACvE,MAAM,IAAI,GAAG,KAAK,C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;oBAE3E,QAAQ,CAAC,gBAAgB,EAAE,uBAAuB,EAAE,aAAa,CAAC,CAAC;oBACnE,QAAQ,CAAC,gBAAgB,EAAE,+BAA+B,EAAE,gBAAgB,CAAC,CAAC;oBAE9E,UAAU,GAAG,IAAI,OAAO,CAAC,KAAK,CAAC;wBAC7B,IAAI,EAAE,MAAM,CAAC,YAAY,CAAC;wBAC1B,SAAS;wBACT,GAAG,gBAAgB;wBACnB,WAAW,EAAE,IAAI;qBAClB,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,UAAU,GAAG,IAAI,OAAO,CAAC,KAAK,CAAC;wBAC7B,gBAAgB;wBAChB,GAAG,YAAY;wBACf,WAAW,EAAE,IAAI;qBACF,CAAC,CAAC;gBACrB,CAAC;gBAED,MAAM,UAAU,CAAC,OAAO,EAAE,CAAC;gBAE3B,MAAM,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC;gBAE9C,IAAI,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,KAAK,EAAE,CAAC;oBACxC,aAAa,CAAC,GAAG,CAAC,qBAAqB,EAAE,UAAU,CAAC,CAAC;oBACrD,aAAa,CAAC,GAAG,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;gBACjD,CAAC;gBAEA,UAAkB,CAAC,IAAI,GAAG,IAAI,CAAC;gBAEhC,OAAO,UAAU,CAAC;YACpB,CAAC;YAED,OAAO,EAAC,IAAI,EAAC,CAAC;QAChB,CAAC;QACD,KAAK,EAAE;YACL,UAAU,CAAC,UAAiB;gBAC1B,OAAO,UAAU,CAAC,UAAU,IAAI,UAAU,CAAC,UAAU,EAAE,CAAC;YAC1D,CAAC;SACF;KACF,CAAC,CAAC;AACL,CAAC"}
1
+ {"version":3,"file":"registerConnectionProvider.js","sourceRoot":"","sources":["../../../src/utils/registerConnectionProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,YAAY,CAAC;AACpC,OAAO,EAAC,aAA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AAC,CAAC;gBAE9C,IAAI,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,KAAK,EAAE,CAAC;oBACxC,aAAa,CAAC,GAAG,CAAC,qBAAqB,EAAE,UAAU,CAAC,CAAC;oBACrD,aAAa,CAAC,GAAG,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;gBACjD,CAAC;gBAEA,UAAkB,CAAC,IAAI,GAAG,IAAI,CAAC;gBAEhC,OAAO,UAAU,CAAC;YACpB,CAAC;YAED,OAAO,EAAC,IAAI,EAAC,CAAC;QAChB,CAAC;QACD,KAAK,EAAE;YACL,UAAU,CAAC,UAAiB;gBAC1B,OAAO,UAAU,CAAC,UAAU,IAAI,UAAU,CAAC,UAAU,EAAE,CAAC;YAC1D,CAAC;SACF;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -2,10 +2,14 @@ import { TokenProvider } from "@tsed/di";
2
2
  import type { Redis } from "ioredis";
3
3
  export interface CreateConnectionProviderProps {
4
4
  token: TokenProvider;
5
+ /**
6
+ * @deprecated use `token` instead of `provide`
7
+ */
8
+ provide?: TokenProvider;
5
9
  name?: string;
6
10
  }
7
11
  export declare const IOREDIS_CONNECTIONS: unique symbol;
8
12
  export type IORedis = Redis & {
9
13
  name: string;
10
14
  };
11
- export declare function registerConnectionProvider({ token, name }: CreateConnectionProviderProps): void;
15
+ export declare function registerConnectionProvider({ token, provide, name }: CreateConnectionProviderProps): void;
package/package.json CHANGED
@@ -2,13 +2,14 @@
2
2
  "name": "@tsed/ioredis",
3
3
  "description": "IO Redis connection for Ts.ED",
4
4
  "type": "module",
5
- "version": "8.0.0",
5
+ "version": "8.0.2",
6
6
  "source": "./src/index.ts",
7
7
  "main": "./lib/esm/index.js",
8
8
  "module": "./lib/esm/index.js",
9
9
  "typings": "./lib/types/index.d.ts",
10
10
  "exports": {
11
11
  ".": {
12
+ "@tsed/source": "./src/index.ts",
12
13
  "types": "./lib/types/index.d.ts",
13
14
  "import": "./lib/esm/index.js",
14
15
  "default": "./lib/esm/index.js"
@@ -25,10 +26,10 @@
25
26
  "tslib": "2.7.0"
26
27
  },
27
28
  "devDependencies": {
28
- "@tsed/barrels": "8.0.0",
29
- "@tsed/core": "8.0.0",
30
- "@tsed/di": "8.0.0",
31
- "@tsed/typescript": "8.0.0",
29
+ "@tsed/barrels": "8.0.2",
30
+ "@tsed/core": "8.0.2",
31
+ "@tsed/di": "8.0.2",
32
+ "@tsed/typescript": "8.0.2",
32
33
  "@types/ioredis-mock": "^8.2.5",
33
34
  "eslint": "9.12.0",
34
35
  "ioredis": "5.4.1",
@@ -37,8 +38,8 @@
37
38
  "vitest": "2.1.2"
38
39
  },
39
40
  "peerDependencies": {
40
- "@tsed/core": "8.0.0",
41
- "@tsed/di": "8.0.0",
41
+ "@tsed/core": "8.0.2",
42
+ "@tsed/di": "8.0.2",
42
43
  "ioredis": ">=5.2.3",
43
44
  "ioredis-mock": ">=8.2.2"
44
45
  },
package/readme.md CHANGED
@@ -59,7 +59,7 @@ export const REDIS_CONNECTION = Symbol.for("REDIS_CONNECTION");
59
59
  export type REDIS_CONNECTION = Redis;
60
60
 
61
61
  registerConnectionProvider({
62
- provide: REDIS_CONNECTION,
62
+ token: REDIS_CONNECTION,
63
63
  name: "default"
64
64
  });
65
65
  ```
@@ -0,0 +1,20 @@
1
+ import {TokenProvider} from "@tsed/di";
2
+ import {Cluster, ClusterOptions, Redis, RedisOptions} from "ioredis";
3
+
4
+ export type ClusterConfiguration = {nodes: string[]} & ClusterOptions;
5
+
6
+ export interface BaseIORedisConfiguration {
7
+ name?: TokenProvider;
8
+ cache?: boolean;
9
+ }
10
+
11
+ export type IORedisConfiguration = BaseIORedisConfiguration &
12
+ (RedisOptions | ClusterConfiguration) & {redisInstance?: Redis | Cluster; sentinelName?: string};
13
+
14
+ declare global {
15
+ namespace TsED {
16
+ interface Configuration {
17
+ ioredis?: IORedisConfiguration[];
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,416 @@
1
+ import {catchAsyncError} from "@tsed/core";
2
+ import {Hooks} from "@tsed/hooks";
3
+ import {type Cache, caching} from "cache-manager";
4
+ import {Redis} from "ioredis";
5
+
6
+ import {IORedisStore, ioRedisStore} from "./IORedisStore.js";
7
+
8
+ vi.mock("ioredis", () => {
9
+ class Redis {
10
+ static Cluster = class {
11
+ hooks = new Hooks();
12
+ connector: any = {};
13
+
14
+ constructor(protected options: any = {}) {
15
+ this.connector.options = options;
16
+ setTimeout(() => {
17
+ this.hooks.emit("ready");
18
+ }, 10);
19
+ }
20
+
21
+ once(...args: any[]) {
22
+ (this.hooks.on as any)(...args);
23
+ return this;
24
+ }
25
+
26
+ disconnect() {
27
+ return undefined;
28
+ }
29
+ };
30
+
31
+ hooks = new Hooks();
32
+ cache = new Map();
33
+ connector: any = {};
34
+
35
+ constructor(protected options: any = {}) {
36
+ this.connector.options = options;
37
+ setTimeout(() => {
38
+ this.hooks.emit("ready");
39
+ }, 10);
40
+ }
41
+
42
+ once(...args: any[]) {
43
+ (this.hooks.on as any)(...args);
44
+ return this;
45
+ }
46
+
47
+ async del(keys: string | string[]) {
48
+ await Promise.all(([] as string[]).concat(keys).map((key) => this.cache.delete(key)));
49
+ }
50
+
51
+ mdel(keys: string[]) {
52
+ return Promise.resolve();
53
+ }
54
+
55
+ flushdb() {
56
+ this.cache.clear();
57
+ return Promise.resolve("OK");
58
+ }
59
+
60
+ flushall() {
61
+ this.cache.clear();
62
+ return Promise.resolve("OK");
63
+ }
64
+
65
+ reset() {
66
+ return Promise.resolve();
67
+ }
68
+
69
+ setex(key: string, ttl: any, value: any) {
70
+ this.cache.set(key, {value, ttl});
71
+ return Promise.resolve("OK");
72
+ }
73
+
74
+ set(key: string, value: any) {
75
+ this.cache.set(key, {value, ttl: -1});
76
+ return Promise.resolve("OK");
77
+ }
78
+
79
+ get(key: string) {
80
+ const cached = this.cache.get(key);
81
+
82
+ if (!cached) {
83
+ throw new Error("missing key");
84
+ }
85
+ return Promise.resolve(cached.value);
86
+ }
87
+
88
+ mget(keys: string[]) {
89
+ return Promise.resolve(keys.map((key) => this.cache.get(key)?.value));
90
+ }
91
+
92
+ mset(keys: [string, unknown][]) {
93
+ return Promise.resolve(keys.map(([key, value]) => this.cache.set(key, value)));
94
+ }
95
+
96
+ multi() {
97
+ return this;
98
+ }
99
+
100
+ exec() {}
101
+
102
+ ttl(key: string) {
103
+ const cached = this.cache.get(key);
104
+ return Promise.resolve(cached?.ttl || -1);
105
+ }
106
+
107
+ end() {
108
+ return Promise.resolve(this);
109
+ }
110
+
111
+ keys() {
112
+ return [...this.cache.keys()];
113
+ }
114
+
115
+ disconnect() {
116
+ return undefined;
117
+ }
118
+ }
119
+
120
+ return {
121
+ default: {Redis},
122
+ Redis
123
+ };
124
+ });
125
+
126
+ let redisCache: Cache<IORedisStore>;
127
+ let customRedisCache: Cache<IORedisStore>;
128
+
129
+ const config = {
130
+ host: "127.0.0.1",
131
+ port: 6379,
132
+ password: null,
133
+ db: 0,
134
+ ttl: 5
135
+ };
136
+
137
+ describe("RedisStore", () => {
138
+ beforeEach(async () => {
139
+ redisCache = await caching(ioRedisStore, {
140
+ host: config.host,
141
+ port: config.port,
142
+ password: config.password,
143
+ db: config.db,
144
+ ttl: config.ttl
145
+ });
146
+
147
+ customRedisCache = await caching(ioRedisStore, {
148
+ host: config.host,
149
+ port: config.port,
150
+ password: config.password,
151
+ db: config.db,
152
+ ttl: config.ttl,
153
+ isCacheableValue: (val?: any) => {
154
+ if (val === undefined) {
155
+ // allow undefined
156
+ return true;
157
+ } else if (val === "FooBarString") {
158
+ // disallow FooBarString
159
+ return false;
160
+ }
161
+ return redisCache.store.isCacheableValue(val);
162
+ }
163
+ });
164
+
165
+ return new Promise((resolve) => {
166
+ redisCache.store.client.once("ready", () => {
167
+ redisCache.reset().then(resolve);
168
+ });
169
+ });
170
+ });
171
+ afterEach(async () => {
172
+ await redisCache.store.client.disconnect(true);
173
+ });
174
+ describe("initialization", () => {
175
+ it("should create a store with password instead of auth_pass (auth_pass is deprecated for redis > 2.5)", async () => {
176
+ const redisPwdCache = await caching(ioRedisStore, {
177
+ host: config.host,
178
+ port: config.port,
179
+ password: config.password,
180
+ db: config.db,
181
+ ttl: config.ttl
182
+ });
183
+
184
+ expect((redisPwdCache.store as any).getClient().options.password).toEqual(config.password);
185
+ });
186
+ it("should create redis store", () => {
187
+ const redisStore = new IORedisStore({
188
+ host: config.host,
189
+ port: config.port,
190
+ db: config.db,
191
+ ttl: config.ttl
192
+ });
193
+
194
+ expect(redisStore.getClient()).toBeInstanceOf(Redis);
195
+ });
196
+
197
+ it("should create a store clusterConfig", () => {
198
+ caching(ioRedisStore, {
199
+ clusterConfig: {
200
+ nodes: [],
201
+ config: {}
202
+ },
203
+ ttl: config.ttl
204
+ });
205
+ });
206
+ });
207
+ describe("mset", () => {
208
+ beforeEach(() => {
209
+ vi.spyOn(redisCache.store.client, "setex");
210
+ vi.spyOn(redisCache.store.client, "mset");
211
+ });
212
+ afterEach(() => {
213
+ vi.resetAllMocks();
214
+ });
215
+ it("should return a promise", () => {
216
+ expect(redisCache.set("foo", "bar")).toBeInstanceOf(Promise);
217
+ });
218
+
219
+ it("should set multiple value with ttl using multi transaction", async () => {
220
+ const result = await redisCache.store.mset([["foo", "bar"]]);
221
+ expect(result).toEqual(undefined);
222
+
223
+ expect(redisCache.store.client.setex).toHaveBeenCalledWith("foo", 0.005, '"bar"');
224
+ });
225
+
226
+ it("should set multiple value with ttl using .set()", async () => {
227
+ (redisCache.store as any).storeArgs.ttl = undefined;
228
+
229
+ const result2 = await redisCache.store.mset([["foo", "bar"]]);
230
+
231
+ expect(result2).toEqual(undefined);
232
+ expect(redisCache.store.client.mset).toHaveBeenCalledWith(["foo", '"bar"']);
233
+ });
234
+
235
+ it("should set multiple value with ttl", async () => {
236
+ const result = await redisCache.store.mset([["foo", "bar"]], 300);
237
+ expect(result).toEqual(undefined);
238
+ });
239
+ });
240
+
241
+ describe("set", () => {
242
+ it("should return a promise", () => {
243
+ expect(redisCache.set("foo", "bar")).toBeInstanceOf(Promise);
244
+ });
245
+
246
+ it("should resolve promise on success (setex)", async () => {
247
+ const result = await redisCache.set("foo", "bar");
248
+ expect(result).toEqual(undefined);
249
+ });
250
+
251
+ it("should resolve promise on success", async () => {
252
+ const result = await redisCache.set("foo", "bar");
253
+ expect(result).toEqual(undefined);
254
+ });
255
+
256
+ it("should reject promise on error", async () => {
257
+ const error = await catchAsyncError(() => redisCache.set("foo", null));
258
+ expect(!!error).toEqual(true);
259
+ });
260
+
261
+ it("should not be able to store a null value (not cacheable)", async () => {
262
+ const error = await catchAsyncError(() => redisCache.set("foo2", null));
263
+
264
+ expect(error?.message).toEqual('"null" is not a cacheable value');
265
+ });
266
+
267
+ it("should store a value without callback", async () => {
268
+ await redisCache.set("foo", "baz");
269
+
270
+ const value = await redisCache.get("foo");
271
+ expect(value).toEqual("baz");
272
+ });
273
+
274
+ it("should not store an invalid value", async () => {
275
+ const err = await catchAsyncError(() => redisCache.set("foo1", undefined));
276
+ expect(err?.message).toEqual('""undefined"" is not a cacheable value');
277
+ });
278
+
279
+ it("should store an undefined value if permitted by isCacheableValue", async () => {
280
+ expect(customRedisCache.store.isCacheable(undefined)).toBe(true);
281
+
282
+ await customRedisCache.set("foo3", undefined);
283
+
284
+ const data = await customRedisCache.get("foo3");
285
+ expect(data).toEqual("undefined");
286
+ });
287
+
288
+ it("should not store a value disallowed by isCacheableValue", async () => {
289
+ expect(customRedisCache.store.isCacheable("FooBarString")).toBe(false);
290
+
291
+ const err = await catchAsyncError(() => customRedisCache.set("foobar", "FooBarString"));
292
+
293
+ expect(err?.message).toEqual('""FooBarString"" is not a cacheable value');
294
+ });
295
+ });
296
+
297
+ describe("get", () => {
298
+ it("should resolve promise on success", async () => {
299
+ await redisCache.set("foo", "bar");
300
+ const result = await redisCache.get("foo");
301
+ expect(result).toEqual("bar");
302
+ });
303
+ it("should reject promise on error", async () => {
304
+ const error = await catchAsyncError(() => redisCache.get("foo2"));
305
+ expect(!!error).toEqual(true);
306
+ });
307
+ it("should retrieve a value for a given key", async () => {
308
+ const value = "bar";
309
+ await redisCache.set("foo", value);
310
+ const result = await redisCache.get("foo");
311
+ expect(result).toEqual(value);
312
+ });
313
+ it("should retrieve a value for a given key if options provided", async () => {
314
+ const value = "bar";
315
+
316
+ await redisCache.set("foo", value);
317
+ const result = await redisCache.get("foo");
318
+ expect(result).toEqual(value);
319
+ });
320
+ });
321
+
322
+ describe("mget", () => {
323
+ it("should resolve promise on success", async () => {
324
+ await redisCache.set("foo", "bar");
325
+ const result = await redisCache.store.mget("foo");
326
+ expect(result).toEqual(["bar"]);
327
+ });
328
+ });
329
+
330
+ describe("del", () => {
331
+ it("should delete a value for a given key", async () => {
332
+ await redisCache.set("foo", "bar");
333
+ await redisCache.del("foo");
334
+ });
335
+ });
336
+
337
+ describe("mdel", () => {
338
+ it("should delete a value for a given key", async () => {
339
+ await redisCache.set("foo", "bar");
340
+ await redisCache.store.mdel("foo");
341
+ const result = await catchAsyncError(() => redisCache.get("foo"));
342
+ expect(result?.message).toEqual("missing key");
343
+ });
344
+ });
345
+
346
+ describe("reset", () => {
347
+ it("should flush underlying db", () => {
348
+ redisCache.reset();
349
+ });
350
+ });
351
+
352
+ describe("ttl", () => {
353
+ it("should retrieve ttl for a given key", async () => {
354
+ await redisCache.set("foo", "bar", 5);
355
+ const ttl = await redisCache.store.ttl("foo");
356
+
357
+ expect(ttl).toEqual(config.ttl);
358
+ });
359
+ });
360
+
361
+ describe("keys", () => {
362
+ it("should resolve promise on success", async () => {
363
+ await redisCache.set("foo", "bar");
364
+ const keys = await redisCache.store.keys("f*");
365
+ expect(keys).toEqual(["foo"]);
366
+ });
367
+
368
+ it("should return an array of keys for the given pattern", async () => {
369
+ await redisCache.set("foo", "bar");
370
+ const arrayOfKeys = await redisCache.store.keys("f*");
371
+ expect(arrayOfKeys).not.toEqual(null);
372
+ expect(arrayOfKeys.indexOf("foo")).not.toEqual(-1);
373
+ });
374
+
375
+ it("should return an array of keys without pattern", async () => {
376
+ await redisCache.set("foo", "bar");
377
+ const arrayOfKeys = await redisCache.store.keys();
378
+
379
+ expect(arrayOfKeys).not.toEqual(null);
380
+ });
381
+ });
382
+
383
+ describe("isCacheableValue", () => {
384
+ it("should return true when the value is not undefined", () => {
385
+ expect(redisCache.store.isCacheable(0)).toBe(true);
386
+ expect(redisCache.store.isCacheable(100)).toBe(true);
387
+ expect(redisCache.store.isCacheable("")).toBe(true);
388
+ expect(redisCache.store.isCacheable("test")).toBe(true);
389
+ });
390
+
391
+ it("should return false when the value is undefined", () => {
392
+ expect(redisCache.store.isCacheable(undefined)).toBe(false);
393
+ });
394
+
395
+ it("should return false when the value is null", () => {
396
+ expect(redisCache.store.isCacheable(null)).toBe(false);
397
+ });
398
+ });
399
+
400
+ describe("overridable isCacheableValue function", () => {
401
+ let redisCache2: any;
402
+
403
+ beforeEach(async () => {
404
+ redisCache2 = await caching(ioRedisStore, {
405
+ ttl: 60,
406
+ isCacheableValue: () => {
407
+ return "I was overridden" as any;
408
+ }
409
+ });
410
+ });
411
+
412
+ it("should return its return value instead of the built-in function", () => {
413
+ expect(redisCache2.store.isCacheableValue(0)).toEqual("I was overridden");
414
+ });
415
+ });
416
+ });
@@ -0,0 +1,131 @@
1
+ import type {Config, FactoryConfig, Store} from "cache-manager";
2
+ import type {Cluster, ClusterNode, ClusterOptions, Redis, RedisOptions} from "ioredis";
3
+ import ioredis from "ioredis";
4
+
5
+ export interface RedisClusterConfig {
6
+ nodes: ClusterNode[];
7
+ options?: ClusterOptions;
8
+ }
9
+
10
+ const getVal = (value: unknown) => JSON.stringify(value) || '"undefined"';
11
+
12
+ export type IORedisStoreCtrOptions = (RedisOptions | {clusterConfig: RedisClusterConfig}) & Config & {redisInstance?: Redis | Cluster};
13
+
14
+ export class IORedisStore implements Store {
15
+ public name = "redis";
16
+ /**
17
+ * @deprecated
18
+ */
19
+ public isCacheableValue;
20
+ public isCacheable;
21
+ private redisCache: Redis | Cluster;
22
+ private storeArgs: any;
23
+
24
+ constructor(options?: IORedisStoreCtrOptions) {
25
+ options = options || {};
26
+
27
+ this.redisCache =
28
+ options.redisInstance ||
29
+ ("clusterConfig" in options
30
+ ? new ioredis.Redis.Cluster(options.clusterConfig.nodes, options.clusterConfig.options)
31
+ : new ioredis.Redis(options));
32
+
33
+ this.storeArgs = this.redisCache.options;
34
+ this.isCacheable = this.isCacheableValue =
35
+ this.storeArgs.isCacheable || this.storeArgs.isCacheableValue || ((value: any) => value !== undefined && value !== null);
36
+ }
37
+
38
+ get client() {
39
+ return this.redisCache;
40
+ }
41
+
42
+ getClient() {
43
+ return this.redisCache;
44
+ }
45
+
46
+ async set(key: string, value: any, ttl?: number) {
47
+ this.assertCacheable(value);
48
+
49
+ ttl = this.getTtl(ttl);
50
+
51
+ const val = getVal(value);
52
+
53
+ if (ttl) {
54
+ await this.redisCache.setex(key, ttl, val);
55
+ return;
56
+ }
57
+
58
+ await this.redisCache.set(key, val);
59
+ }
60
+
61
+ async get<T = any>(key: string, options?: any) {
62
+ const val = await this.redisCache.get(key);
63
+
64
+ if (val === undefined || val === null) {
65
+ return undefined;
66
+ }
67
+
68
+ return JSON.parse(val) as T;
69
+ }
70
+
71
+ async del(key: string) {
72
+ await this.redisCache.del(key);
73
+ }
74
+
75
+ async mset(args: [string, unknown][], ttl?: number) {
76
+ ttl = this.getTtl(ttl);
77
+
78
+ if (ttl) {
79
+ const multi = this.redisCache.multi();
80
+
81
+ for (const [key, value] of args) {
82
+ this.assertCacheable(value);
83
+
84
+ multi.setex(key, ttl / 1000, getVal(value));
85
+ }
86
+
87
+ await multi.exec();
88
+ } else
89
+ await this.redisCache.mset(
90
+ args.flatMap(([key, value]) => {
91
+ this.assertCacheable(value);
92
+
93
+ return [key, getVal(value)] as [string, string];
94
+ })
95
+ );
96
+ }
97
+
98
+ async mget(...args: string[]) {
99
+ const x = await this.redisCache.mget(args);
100
+
101
+ return x.map((x) => (x === null || x === undefined ? undefined : (JSON.parse(x) as unknown)));
102
+ }
103
+
104
+ async mdel(...args: string[]) {
105
+ await this.redisCache.del(args);
106
+ }
107
+
108
+ async reset() {
109
+ await this.redisCache.flushall();
110
+ }
111
+
112
+ keys(pattern: string = "*") {
113
+ return this.redisCache.keys(pattern);
114
+ }
115
+
116
+ ttl(key: string) {
117
+ return this.redisCache.ttl(key);
118
+ }
119
+
120
+ private getTtl(ttl?: number) {
121
+ return ttl === undefined ? this.storeArgs.ttl : ttl;
122
+ }
123
+
124
+ private assertCacheable(value: any) {
125
+ if (!this.isCacheable(value)) {
126
+ throw new Error(`"${getVal(value)}" is not a cacheable value`);
127
+ }
128
+ }
129
+ }
130
+
131
+ export const ioRedisStore = (config?: FactoryConfig<any>) => new IORedisStore(config);
@@ -0,0 +1,28 @@
1
+ import {Inject, Injectable} from "@tsed/di";
2
+ import type {Redis} from "ioredis";
3
+ import RedisMock from "ioredis-mock";
4
+
5
+ import {registerConnectionProvider} from "../utils/registerConnectionProvider.js";
6
+ import {IORedisTest} from "./IORedisTest.js";
7
+
8
+ const MY_CONNECTION = Symbol("MY_CONNECTION");
9
+ type MY_CONNECTION = Redis;
10
+
11
+ registerConnectionProvider({token: MY_CONNECTION, name: "default"});
12
+
13
+ @Injectable()
14
+ class MyRepository {
15
+ @Inject(MY_CONNECTION)
16
+ connection: MY_CONNECTION;
17
+ }
18
+
19
+ describe("IORedisTest", () => {
20
+ beforeEach(() => IORedisTest.create());
21
+ afterEach(() => IORedisTest.reset());
22
+
23
+ it("should create mocked connection", () => {
24
+ const service = IORedisTest.get(MyRepository);
25
+
26
+ expect(service.connection).toBeInstanceOf(RedisMock);
27
+ });
28
+ });
@@ -0,0 +1,16 @@
1
+ import {DITest} from "@tsed/di";
2
+
3
+ import {mockConnections} from "../utils/mockConnections.js";
4
+
5
+ export class IORedisTest extends DITest {
6
+ static async create(options?: Partial<TsED.Configuration>) {
7
+ const imports = await mockConnections();
8
+
9
+ await Promise.all(imports.map(({use}) => use.flushall()));
10
+
11
+ return DITest.create({
12
+ ...options,
13
+ imports: [...(options?.imports || []), ...imports]
14
+ });
15
+ }
16
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @file Automatically generated by @tsed/barrels.
3
+ */
4
+ export * from "./domain/IORedisConfiguration.js";
5
+ export * from "./domain/IORedisStore.js";
6
+ export * from "./domain/IORedisTest.js";
7
+ export * from "./utils/mockConnections.js";
8
+ export * from "./utils/registerConnectionProvider.js";
@@ -0,0 +1,24 @@
1
+ import {GlobalProviders, TokenProvider} from "@tsed/di";
2
+ import type {Redis} from "ioredis";
3
+
4
+ import {IOREDIS_CONNECTIONS} from "./registerConnectionProvider.js";
5
+
6
+ export async function mockConnection(token: TokenProvider, name: string) {
7
+ const {default: RealIORedis} = await import("ioredis-mock");
8
+ const connection: Redis = new (RealIORedis as any)();
9
+
10
+ (connection as any).name = name;
11
+
12
+ return {
13
+ token,
14
+ use: connection
15
+ };
16
+ }
17
+
18
+ export function mockConnections() {
19
+ return Promise.all(
20
+ [...GlobalProviders.values()]
21
+ .filter((provider) => provider.type === IOREDIS_CONNECTIONS)
22
+ .map((provider) => mockConnection(provider.token, provider.connectionName))
23
+ );
24
+ }
@@ -0,0 +1,163 @@
1
+ import {configuration, DITest} from "@tsed/di";
2
+ import {Redis} from "ioredis";
3
+
4
+ import {registerConnectionProvider} from "./registerConnectionProvider.js";
5
+
6
+ vi.mock("ioredis", () => {
7
+ class MockRedis {
8
+ static Cluster = class {
9
+ connector: any = {};
10
+
11
+ constructor(
12
+ public nodes: any,
13
+ public options: any
14
+ ) {
15
+ this.connector.options = options;
16
+ }
17
+
18
+ connect() {
19
+ return Promise.resolve(undefined);
20
+ }
21
+
22
+ disconnect() {
23
+ return Promise.resolve(undefined);
24
+ }
25
+ };
26
+ connector: any = {};
27
+
28
+ constructor(public options: any) {
29
+ this.connector.options = options;
30
+ }
31
+
32
+ connect() {
33
+ return Promise.resolve(undefined);
34
+ }
35
+
36
+ disconnect() {
37
+ return Promise.resolve(undefined);
38
+ }
39
+ }
40
+
41
+ return {Redis: MockRedis, default: {Redis: MockRedis}};
42
+ });
43
+
44
+ const REDIS_CONNECTION = Symbol.for("REDIS_CONNECTION");
45
+ type REDIS_CONNECTION = Redis;
46
+
47
+ registerConnectionProvider({token: REDIS_CONNECTION, name: "default"});
48
+
49
+ describe("RedisConnection", () => {
50
+ describe("Redis", () => {
51
+ beforeEach(() =>
52
+ DITest.create({
53
+ ioredis: [
54
+ {
55
+ name: "default",
56
+ host: "localhost",
57
+ cache: true
58
+ }
59
+ ],
60
+ cache: {} as any
61
+ })
62
+ );
63
+ afterEach(() => DITest.reset());
64
+
65
+ it("should create redis connection", () => {
66
+ const connection = DITest.get<REDIS_CONNECTION>(REDIS_CONNECTION);
67
+ const cacheSettings = configuration().get("cache");
68
+
69
+ expect((connection as any).options).toMatchObject({
70
+ host: "localhost",
71
+ lazyConnect: true,
72
+ reconnectOnError: expect.any(Function)
73
+ });
74
+ expect(cacheSettings.redisInstance).toEqual(connection);
75
+ });
76
+ });
77
+ describe("Cluster", () => {
78
+ beforeEach(() =>
79
+ DITest.create({
80
+ ioredis: [
81
+ {
82
+ name: "default",
83
+ cache: true,
84
+ nodes: [],
85
+ redisOptions: {},
86
+ value: "value"
87
+ } as any
88
+ ],
89
+ cache: {} as any
90
+ })
91
+ );
92
+ afterEach(() => DITest.reset());
93
+
94
+ it("should create redis connection", () => {
95
+ const connection = DITest.get<REDIS_CONNECTION>(REDIS_CONNECTION);
96
+ const cacheSettings = configuration().get("cache");
97
+
98
+ expect((connection as any).options).toMatchObject({
99
+ clusterRetryStrategy: expect.any(Function),
100
+ value: "value",
101
+ lazyConnect: true,
102
+ redisOptions: {
103
+ reconnectOnError: expect.any(Function)
104
+ }
105
+ });
106
+ expect((connection as any).nodes).toEqual([]);
107
+ expect(cacheSettings.redisInstance).toEqual(connection);
108
+
109
+ (connection as any).options.clusterRetryStrategy();
110
+ (connection as any).options.redisOptions.reconnectOnError();
111
+ });
112
+ });
113
+ describe("Sentinel", () => {
114
+ beforeEach(() =>
115
+ DITest.create({
116
+ ioredis: [
117
+ {
118
+ name: "default",
119
+ cache: true,
120
+ sentinels: [],
121
+ sentinelName: "sentinelName",
122
+ redisOptions: {},
123
+ value: "value"
124
+ } as any
125
+ ],
126
+ cache: {} as any
127
+ })
128
+ );
129
+ afterEach(() => DITest.reset());
130
+
131
+ it("should create redis connection", () => {
132
+ const connection = DITest.get<REDIS_CONNECTION>(REDIS_CONNECTION);
133
+ const cacheSettings = configuration().get("cache");
134
+
135
+ expect((connection as any).options).toMatchObject({
136
+ value: "value",
137
+ lazyConnect: true
138
+ });
139
+ expect((connection as any).options.sentinels).toEqual([]);
140
+ expect((connection as any).options.name).toEqual("sentinelName");
141
+ expect(cacheSettings.redisInstance).toEqual(connection);
142
+
143
+ (connection as any).options.sentinelRetryStrategy();
144
+ });
145
+ });
146
+ describe("Disabled connection", () => {
147
+ beforeEach(() =>
148
+ DITest.create({
149
+ ioredis: [],
150
+ cache: {} as any
151
+ })
152
+ );
153
+ afterEach(() => DITest.reset());
154
+
155
+ it("should create redis connection", () => {
156
+ const connection = DITest.get<REDIS_CONNECTION>(REDIS_CONNECTION);
157
+
158
+ expect(connection).toEqual({
159
+ name: "default"
160
+ });
161
+ });
162
+ });
163
+ });
@@ -0,0 +1,100 @@
1
+ import {setValue} from "@tsed/core";
2
+ import {Configuration, registerProvider, TokenProvider} from "@tsed/di";
3
+ import {Logger} from "@tsed/logger";
4
+ import type {Cluster, Redis, RedisOptions} from "ioredis";
5
+ import ioredis from "ioredis";
6
+
7
+ import {IORedisConfiguration} from "../domain/IORedisConfiguration.js";
8
+ import {ioRedisStore} from "../domain/IORedisStore.js";
9
+
10
+ export interface CreateConnectionProviderProps {
11
+ token: TokenProvider;
12
+ /**
13
+ * @deprecated use `token` instead of `provide`
14
+ */
15
+ provide?: TokenProvider;
16
+ name?: string;
17
+ }
18
+
19
+ export const IOREDIS_CONNECTIONS = Symbol.for("ioredis:connections");
20
+ export type IORedis = Redis & {name: string};
21
+
22
+ export function registerConnectionProvider({token, provide, name = "default"}: CreateConnectionProviderProps) {
23
+ registerProvider({
24
+ token: provide || token,
25
+ type: IOREDIS_CONNECTIONS,
26
+ connectionName: name,
27
+ deps: [Configuration, Logger],
28
+ async useAsyncFactory(configuration: Configuration, logger: Logger) {
29
+ const items = configuration.get<IORedisConfiguration[]>("ioredis", []);
30
+ const item = items.find((item) => item.name === name);
31
+ const retryStrategy = (times: number) => {
32
+ logger.fatal({event: "REDIS_ERROR", message: `Redis is not responding - Retry count: ${times}`});
33
+ return 2000;
34
+ };
35
+
36
+ if (item) {
37
+ const {name, cache, ...redisOptions} = item;
38
+ let connection: Cluster | Redis;
39
+
40
+ const reconnectOnError = (err: any) => {
41
+ logger.fatal({
42
+ event: "REDIS_ERROR",
43
+ message: `Redis - Reconnect on error: ${(err && err.message) || err}`,
44
+ stack: err?.stack
45
+ });
46
+ };
47
+
48
+ if ("nodes" in redisOptions) {
49
+ const {nodes, ...clusterOptions} = redisOptions;
50
+
51
+ setValue(clusterOptions, "clusterRetryStrategy", retryStrategy);
52
+ setValue(clusterOptions, "redisOptions.reconnectOnError", reconnectOnError);
53
+
54
+ connection = new ioredis.Redis.Cluster(nodes, {
55
+ ...clusterOptions,
56
+ lazyConnect: true
57
+ });
58
+ } else if ("sentinels" in redisOptions) {
59
+ const {sentinels, sentinelName = name, ...sentinelsOptions} = redisOptions;
60
+
61
+ setValue(sentinelsOptions, "sentinelRetryStrategy", retryStrategy);
62
+ setValue(sentinelsOptions, "redisOptions.reconnectOnError", reconnectOnError);
63
+
64
+ connection = new ioredis.Redis({
65
+ name: String(sentinelName),
66
+ sentinels,
67
+ ...sentinelsOptions,
68
+ lazyConnect: true
69
+ });
70
+ } else {
71
+ connection = new ioredis.Redis({
72
+ reconnectOnError,
73
+ ...redisOptions,
74
+ lazyConnect: true
75
+ } as RedisOptions);
76
+ }
77
+
78
+ await connection.connect();
79
+
80
+ logger.info("Connected to redis database...");
81
+
82
+ if (configuration.get("cache") && cache) {
83
+ configuration.set("cache.redisInstance", connection);
84
+ configuration.set("cache.store", ioRedisStore);
85
+ }
86
+
87
+ (connection as any).name = name;
88
+
89
+ return connection;
90
+ }
91
+
92
+ return {name};
93
+ },
94
+ hooks: {
95
+ $onDestroy(connection: Redis) {
96
+ return connection.disconnect && connection.disconnect();
97
+ }
98
+ }
99
+ });
100
+ }