@tsed/ioredis 6.129.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/.nycrc +26 -0
- package/jest.config.js +14 -0
- package/lib/cjs/domain/IORedisConfiguration.js +3 -0
- package/lib/cjs/domain/IORedisConfiguration.js.map +1 -0
- package/lib/cjs/domain/IORedisStore.js +92 -0
- package/lib/cjs/domain/IORedisStore.js.map +1 -0
- package/lib/cjs/domain/IORedisTest.js +18 -0
- package/lib/cjs/domain/IORedisTest.js.map +1 -0
- package/lib/cjs/index.js +12 -0
- package/lib/cjs/index.js.map +1 -0
- package/lib/cjs/package.json +3 -0
- package/lib/cjs/utils/mockConnections.js +23 -0
- package/lib/cjs/utils/mockConnections.js.map +1 -0
- package/lib/cjs/utils/registerConnectionProvider.js +69 -0
- package/lib/cjs/utils/registerConnectionProvider.js.map +1 -0
- package/lib/esm/domain/IORedisConfiguration.js +2 -0
- package/lib/esm/domain/IORedisConfiguration.js.map +1 -0
- package/lib/esm/domain/IORedisStore.js +87 -0
- package/lib/esm/domain/IORedisStore.js.map +1 -0
- package/lib/esm/domain/IORedisTest.js +14 -0
- package/lib/esm/domain/IORedisTest.js.map +1 -0
- package/lib/esm/index.js +9 -0
- package/lib/esm/index.js.map +1 -0
- package/lib/esm/package.json +3 -0
- package/lib/esm/utils/mockConnections.js +17 -0
- package/lib/esm/utils/mockConnections.js.map +1 -0
- package/lib/esm/utils/registerConnectionProvider.js +64 -0
- package/lib/esm/utils/registerConnectionProvider.js.map +1 -0
- package/lib/types/domain/IORedisConfiguration.d.ts +17 -0
- package/lib/types/domain/IORedisStore.d.ts +20 -0
- package/lib/types/domain/IORedisTest.d.ts +4 -0
- package/lib/types/index.d.ts +8 -0
- package/lib/types/utils/mockConnections.d.ts +10 -0
- package/lib/types/utils/registerConnectionProvider.d.ts +11 -0
- package/package.json +46 -0
- package/readme.md +288 -0
- package/tsconfig.compile.esm.json +12 -0
package/.nycrc
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"include": [
|
|
3
|
+
"src/**/*.ts"
|
|
4
|
+
],
|
|
5
|
+
"exclude": [
|
|
6
|
+
"**/*.d.ts",
|
|
7
|
+
"node_modules",
|
|
8
|
+
"**/interfaces/**",
|
|
9
|
+
"**/index.ts"
|
|
10
|
+
],
|
|
11
|
+
"extension": [
|
|
12
|
+
".ts"
|
|
13
|
+
],
|
|
14
|
+
"require": [],
|
|
15
|
+
"reporter": [
|
|
16
|
+
"text-summary",
|
|
17
|
+
"html",
|
|
18
|
+
"lcov",
|
|
19
|
+
"json"
|
|
20
|
+
],
|
|
21
|
+
"check-coverage": true,
|
|
22
|
+
"statements": 100,
|
|
23
|
+
"branches": 78.22,
|
|
24
|
+
"functions": 100,
|
|
25
|
+
"lines": 100
|
|
26
|
+
}
|
package/jest.config.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// For a detailed explanation regarding each configuration property, visit:
|
|
2
|
+
// https://jestjs.io/docs/en/configuration.html
|
|
3
|
+
|
|
4
|
+
module.exports = {
|
|
5
|
+
...require("@tsed/jest-config")(__dirname, "adapters-redis"),
|
|
6
|
+
coverageThreshold: {
|
|
7
|
+
global: {
|
|
8
|
+
branches: 70,
|
|
9
|
+
functions: 70,
|
|
10
|
+
lines: 70,
|
|
11
|
+
statements: 70
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IORedisConfiguration.js","sourceRoot":"","sources":["../../../src/domain/IORedisConfiguration.ts"],"names":[],"mappings":"","sourcesContent":["import {TokenProvider} from \"@tsed/di\";\nimport {ClusterOptions, RedisOptions} from \"ioredis\";\n\nexport type ClusterConfiguration = {nodes: string[]} & ClusterOptions;\n\nexport interface BaseIORedisConfiguration {\n name?: TokenProvider;\n cache?: boolean;\n}\n\nexport type IORedisConfiguration = BaseIORedisConfiguration & (RedisOptions | ClusterConfiguration);\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace TsED {\n interface Configuration {\n ioredis?: IORedisConfiguration[];\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ioRedisStore = exports.IORedisStore = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const ioredis_1 = tslib_1.__importDefault(require("ioredis"));
|
|
6
|
+
async function handle(next, parse, cb) {
|
|
7
|
+
try {
|
|
8
|
+
let result = await next();
|
|
9
|
+
if (parse) {
|
|
10
|
+
result = result && JSON.parse(result);
|
|
11
|
+
}
|
|
12
|
+
if (!cb) {
|
|
13
|
+
return result;
|
|
14
|
+
}
|
|
15
|
+
cb(null, result);
|
|
16
|
+
}
|
|
17
|
+
catch (er) {
|
|
18
|
+
if (!cb) {
|
|
19
|
+
throw er;
|
|
20
|
+
}
|
|
21
|
+
cb(er, null);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
class IORedisStore {
|
|
25
|
+
name = "redis";
|
|
26
|
+
isCacheableValue;
|
|
27
|
+
redisCache;
|
|
28
|
+
storeArgs;
|
|
29
|
+
constructor(...args) {
|
|
30
|
+
if (args.length > 0 && args[0].redisInstance) {
|
|
31
|
+
this.redisCache = args[0].redisInstance;
|
|
32
|
+
}
|
|
33
|
+
else if (args.length > 0 && args[0].clusterConfig) {
|
|
34
|
+
const { nodes, options } = args[0].clusterConfig;
|
|
35
|
+
this.redisCache = new ioredis_1.default.Cluster(nodes, options || {});
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
this.redisCache = new ioredis_1.default(...args);
|
|
39
|
+
}
|
|
40
|
+
this.storeArgs = this.redisCache.options;
|
|
41
|
+
this.isCacheableValue = this.storeArgs.isCacheableValue || ((value) => value !== undefined && value !== null);
|
|
42
|
+
}
|
|
43
|
+
getClient() {
|
|
44
|
+
return this.redisCache;
|
|
45
|
+
}
|
|
46
|
+
set(key, value, options, cb) {
|
|
47
|
+
if (typeof options === "function") {
|
|
48
|
+
cb = options;
|
|
49
|
+
options = {};
|
|
50
|
+
}
|
|
51
|
+
options = options || {};
|
|
52
|
+
return handle(async () => {
|
|
53
|
+
if (!this.isCacheableValue(value)) {
|
|
54
|
+
throw new Error(`"${value}" is not a cacheable value`);
|
|
55
|
+
}
|
|
56
|
+
const ttl = options.ttl || options.ttl === 0 ? options.ttl : this.storeArgs.ttl;
|
|
57
|
+
const val = JSON.stringify(value) || '"undefined"';
|
|
58
|
+
if (ttl) {
|
|
59
|
+
return this.redisCache.setex(key, ttl, val);
|
|
60
|
+
}
|
|
61
|
+
return this.redisCache.set(key, val);
|
|
62
|
+
}, false, cb);
|
|
63
|
+
}
|
|
64
|
+
get(key, options, cb) {
|
|
65
|
+
if (typeof options === "function") {
|
|
66
|
+
cb = options;
|
|
67
|
+
}
|
|
68
|
+
return handle(() => this.redisCache.get(key), true, cb);
|
|
69
|
+
}
|
|
70
|
+
del(key, options, cb) {
|
|
71
|
+
if (typeof options === "function") {
|
|
72
|
+
cb = options;
|
|
73
|
+
}
|
|
74
|
+
return handle(() => this.redisCache.del(key), false, cb);
|
|
75
|
+
}
|
|
76
|
+
reset(cb) {
|
|
77
|
+
return handle(() => this.redisCache.flushdb(), false, cb);
|
|
78
|
+
}
|
|
79
|
+
keys(pattern, cb) {
|
|
80
|
+
if (typeof pattern === "function") {
|
|
81
|
+
cb = pattern;
|
|
82
|
+
pattern = "*";
|
|
83
|
+
}
|
|
84
|
+
return handle(() => this.redisCache.keys(pattern), false, cb);
|
|
85
|
+
}
|
|
86
|
+
ttl(key, cb) {
|
|
87
|
+
return handle(() => this.redisCache.ttl(key), false, cb);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
exports.IORedisStore = IORedisStore;
|
|
91
|
+
exports.ioRedisStore = { create: (...args) => new IORedisStore(...args) };
|
|
92
|
+
//# sourceMapping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AAE,EAAE,CAAC,IAAI,YAAY,CAAC,GAAG,IAAI,CAAC,EAAC,CAAC","sourcesContent":["import {Store} from \"cache-manager\";\nimport Redis, {Cluster} from \"ioredis\";\nimport {Callback} from \"ioredis/built/types\";\n\nasync function handle<Response = any>(next: () => Promise<Response>, parse: boolean, cb?: Callback<Response | null>) {\n try {\n let result = await next();\n\n if (parse) {\n result = result && JSON.parse(result as any);\n }\n\n if (!cb) {\n return result;\n }\n\n cb(null, result);\n } catch (er) {\n if (!cb) {\n throw er;\n }\n\n cb(er, null);\n }\n}\n\nexport class IORedisStore implements Store {\n public name = \"redis\";\n public isCacheableValue;\n private redisCache: Redis | Cluster;\n private storeArgs: any;\n\n constructor(...args: any[]) {\n if (args.length > 0 && args[0].redisInstance) {\n this.redisCache = args[0].redisInstance;\n } else if (args.length > 0 && args[0].clusterConfig) {\n const {nodes, options} = args[0].clusterConfig;\n\n this.redisCache = new Redis.Cluster(nodes, options || {});\n } else {\n this.redisCache = new (Redis as any)(...args);\n }\n\n this.storeArgs = this.redisCache.options;\n this.isCacheableValue = this.storeArgs.isCacheableValue || ((value: any) => value !== undefined && value !== null);\n }\n\n getClient() {\n return this.redisCache;\n }\n\n set(key: string, value: any, options: any, cb?: Callback<\"OK\">) {\n if (typeof options === \"function\") {\n cb = options;\n options = {};\n }\n\n options = options || {};\n\n return handle<\"OK\">(\n async () => {\n if (!this.isCacheableValue(value)) {\n throw new Error(`\"${value}\" is not a cacheable value`);\n }\n\n const ttl = options.ttl || options.ttl === 0 ? options.ttl : this.storeArgs.ttl;\n const val = JSON.stringify(value) || '\"undefined\"';\n\n if (ttl) {\n return this.redisCache.setex(key, ttl, val);\n }\n\n return this.redisCache.set(key, val);\n },\n false,\n cb\n );\n }\n\n get(key: string, options?: any, cb?: Callback<string | null>) {\n if (typeof options === \"function\") {\n cb = options;\n }\n\n return handle(() => this.redisCache.get(key), true, cb);\n }\n\n del(key: string, options: any, cb?: Callback<number>) {\n if (typeof options === \"function\") {\n cb = options;\n }\n\n return handle(() => this.redisCache.del(key), false, cb);\n }\n\n reset(cb?: Callback<\"OK\">) {\n return handle(() => this.redisCache.flushdb(), false, cb);\n }\n\n keys(pattern: string, cb: Callback<string[]>) {\n if (typeof pattern === \"function\") {\n cb = pattern;\n pattern = \"*\";\n }\n\n return handle<string[]>(() => this.redisCache.keys(pattern), false, cb);\n }\n\n ttl(key: string, cb?: Callback<number>) {\n return handle<number>(() => this.redisCache.ttl(key), false, cb);\n }\n}\n\nexport const ioRedisStore = {create: (...args: any[]) => new IORedisStore(...args)};\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.IORedisTest = void 0;
|
|
4
|
+
const di_1 = require("@tsed/di");
|
|
5
|
+
const mockConnections_1 = require("../utils/mockConnections");
|
|
6
|
+
class IORedisTest extends di_1.DITest {
|
|
7
|
+
static async create(options) {
|
|
8
|
+
const imports = (0, mockConnections_1.mockConnections)();
|
|
9
|
+
await Promise.all(imports.map(({ use }) => use.flushall()));
|
|
10
|
+
return di_1.DITest.create({
|
|
11
|
+
...IORedisTest.options,
|
|
12
|
+
...options,
|
|
13
|
+
imports: [...(options?.imports || []), ...imports]
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
exports.IORedisTest = IORedisTest;
|
|
18
|
+
//# sourceMappingURL=IORedisTest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IORedisTest.js","sourceRoot":"","sources":["../../../src/domain/IORedisTest.ts"],"names":[],"mappings":";;;AAAA,iCAA+C;AAC/C,8DAAyD;AAEzD,MAAa,WAAY,SAAQ,WAAM;IACrC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAuB;QACzC,MAAM,OAAO,GAAG,IAAA,iCAAe,GAAE,CAAC;QAElC,MAAM,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAE,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;QAE1D,OAAO,WAAM,CAAC,MAAM,CAAC;YACnB,GAAG,WAAW,CAAC,OAAO;YACtB,GAAG,OAAO;YACV,OAAO,EAAE,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,IAAI,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC;SACnD,CAAC,CAAC;IACL,CAAC;CACF;AAZD,kCAYC","sourcesContent":["import {DITest, DITestOptions} from \"@tsed/di\";\nimport {mockConnections} from \"../utils/mockConnections\";\n\nexport class IORedisTest extends DITest {\n static async create(options?: DITestOptions) {\n const imports = mockConnections();\n\n await Promise.all(imports.map(({use}) => use.flushall()));\n\n return DITest.create({\n ...IORedisTest.options,\n ...options,\n imports: [...(options?.imports || []), ...imports]\n });\n }\n}\n"]}
|
package/lib/cjs/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @file Automatically generated by barrelsby.
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
const tslib_1 = require("tslib");
|
|
7
|
+
tslib_1.__exportStar(require("./domain/IORedisConfiguration"), exports);
|
|
8
|
+
tslib_1.__exportStar(require("./domain/IORedisStore"), exports);
|
|
9
|
+
tslib_1.__exportStar(require("./domain/IORedisTest"), exports);
|
|
10
|
+
tslib_1.__exportStar(require("./utils/mockConnections"), exports);
|
|
11
|
+
tslib_1.__exportStar(require("./utils/registerConnectionProvider"), exports);
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAEH,wEAA8C;AAC9C,gEAAsC;AACtC,+DAAqC;AACrC,kEAAwC;AACxC,6EAAmD","sourcesContent":["/**\n * @file Automatically generated by barrelsby.\n */\n\nexport * from \"./domain/IORedisConfiguration\";\nexport * from \"./domain/IORedisStore\";\nexport * from \"./domain/IORedisTest\";\nexport * from \"./utils/mockConnections\";\nexport * from \"./utils/registerConnectionProvider\";\n"]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.mockConnections = exports.mockConnection = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const di_1 = require("@tsed/di");
|
|
6
|
+
const ioredis_mock_1 = tslib_1.__importDefault(require("ioredis-mock"));
|
|
7
|
+
const registerConnectionProvider_1 = require("./registerConnectionProvider");
|
|
8
|
+
function mockConnection(token, name) {
|
|
9
|
+
const connection = new ioredis_mock_1.default();
|
|
10
|
+
connection.name = name;
|
|
11
|
+
return {
|
|
12
|
+
token,
|
|
13
|
+
use: connection
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
exports.mockConnection = mockConnection;
|
|
17
|
+
function mockConnections() {
|
|
18
|
+
return [...di_1.GlobalProviders.values()]
|
|
19
|
+
.filter((provider) => provider.type === registerConnectionProvider_1.IOREDIS_CONNECTIONS)
|
|
20
|
+
.map((provider) => mockConnection(provider.token, provider.connectionName));
|
|
21
|
+
}
|
|
22
|
+
exports.mockConnections = mockConnections;
|
|
23
|
+
//# sourceMappingURL=mockConnections.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mockConnections.js","sourceRoot":"","sources":["../../../src/utils/mockConnections.ts"],"names":[],"mappings":";;;;AAAA,iCAAwD;AAExD,wEAAuC;AACvC,6EAAiE;AAEjE,SAAgB,cAAc,CAAC,KAAoB,EAAE,IAAY;IAC/D,MAAM,UAAU,GAAU,IAAK,sBAAmB,EAAE,CAAC;IAEpD,UAAkB,CAAC,IAAI,GAAG,IAAI,CAAC;IAEhC,OAAO;QACL,KAAK;QACL,GAAG,EAAE,UAAU;KAChB,CAAC;AACJ,CAAC;AATD,wCASC;AAED,SAAgB,eAAe;IAC7B,OAAO,CAAC,GAAG,oBAAe,CAAC,MAAM,EAAE,CAAC;SACjC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,KAAK,gDAAmB,CAAC;SAC3D,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,cAAc,CAAC,CAAC,CAAC;AAChF,CAAC;AAJD,0CAIC","sourcesContent":["import {GlobalProviders, TokenProvider} from \"@tsed/di\";\nimport Redis from \"ioredis\";\nimport RealIORedis from \"ioredis-mock\";\nimport {IOREDIS_CONNECTIONS} from \"./registerConnectionProvider\";\n\nexport function mockConnection(token: TokenProvider, name: string) {\n const connection: Redis = new (RealIORedis as any)();\n\n (connection as any).name = name;\n\n return {\n token,\n use: connection\n };\n}\n\nexport function mockConnections() {\n return [...GlobalProviders.values()]\n .filter((provider) => provider.type === IOREDIS_CONNECTIONS)\n .map((provider) => mockConnection(provider.token, provider.connectionName));\n}\n"]}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerConnectionProvider = exports.IOREDIS_CONNECTIONS = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const core_1 = require("@tsed/core");
|
|
6
|
+
const di_1 = require("@tsed/di");
|
|
7
|
+
const logger_1 = require("@tsed/logger");
|
|
8
|
+
const ioredis_1 = tslib_1.__importDefault(require("ioredis"));
|
|
9
|
+
const IORedisStore_1 = require("../domain/IORedisStore");
|
|
10
|
+
exports.IOREDIS_CONNECTIONS = Symbol.for("ioredis:connections");
|
|
11
|
+
function registerConnectionProvider({ provide, name = "default" }) {
|
|
12
|
+
(0, di_1.registerProvider)({
|
|
13
|
+
provide,
|
|
14
|
+
type: exports.IOREDIS_CONNECTIONS,
|
|
15
|
+
connectionName: name,
|
|
16
|
+
deps: [di_1.Configuration, logger_1.Logger],
|
|
17
|
+
async useAsyncFactory(configuration, logger) {
|
|
18
|
+
const items = configuration.get("ioredis", []);
|
|
19
|
+
const item = items.find((item) => item.name === name);
|
|
20
|
+
if (item) {
|
|
21
|
+
const { name, cache, ...redisOptions } = item;
|
|
22
|
+
let connection;
|
|
23
|
+
const reconnectOnError = (err) => {
|
|
24
|
+
logger.fatal({
|
|
25
|
+
event: "REDIS_ERROR",
|
|
26
|
+
message: `Redis - Reconnect on error: ${(err && err.message) || err}`,
|
|
27
|
+
stack: err?.stack
|
|
28
|
+
});
|
|
29
|
+
};
|
|
30
|
+
if ("nodes" in redisOptions) {
|
|
31
|
+
const { nodes, ...clusterOptions } = redisOptions;
|
|
32
|
+
const clusterRetryStrategy = (times) => {
|
|
33
|
+
logger.fatal({ event: "REDIS_ERROR", message: `Redis is not responding - Retry count: ${times}` });
|
|
34
|
+
return 2000;
|
|
35
|
+
};
|
|
36
|
+
(0, core_1.setValue)(clusterOptions, "clusterRetryStrategy", clusterRetryStrategy);
|
|
37
|
+
(0, core_1.setValue)(clusterOptions, "redisOptions.reconnectOnError", reconnectOnError);
|
|
38
|
+
connection = new ioredis_1.default.Cluster(nodes, {
|
|
39
|
+
...clusterOptions,
|
|
40
|
+
lazyConnect: true
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
connection = new ioredis_1.default({
|
|
45
|
+
...redisOptions,
|
|
46
|
+
lazyConnect: true,
|
|
47
|
+
reconnectOnError
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
await connection.connect();
|
|
51
|
+
logger.info("Connected to redis database...");
|
|
52
|
+
if (configuration.get("cache") && cache) {
|
|
53
|
+
configuration.set("cache.redisInstance", connection);
|
|
54
|
+
configuration.set("cache.store", IORedisStore_1.ioRedisStore);
|
|
55
|
+
}
|
|
56
|
+
connection.name = name;
|
|
57
|
+
return connection;
|
|
58
|
+
}
|
|
59
|
+
return { name };
|
|
60
|
+
},
|
|
61
|
+
hooks: {
|
|
62
|
+
$onDestroy(connection) {
|
|
63
|
+
return connection.disconnect && connection.disconnect();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
exports.registerConnectionProvider = registerConnectionProvider;
|
|
69
|
+
//# sourceMappingURL=registerConnectionProvider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registerConnectionProvider.js","sourceRoot":"","sources":["../../../src/utils/registerConnectionProvider.ts"],"names":[],"mappings":";;;;AAAA,qCAAoC;AACpC,iCAAwE;AACxE,yCAAoC;AACpC,8DAAqD;AAErD,yDAAoD;AAOvC,QAAA,mBAAmB,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAGrE,SAAgB,0BAA0B,CAAC,EAAC,OAAO,EAAE,IAAI,GAAG,SAAS,EAAgC;IACnG,IAAA,qBAAgB,EAAC;QACf,OAAO;QACP,IAAI,EAAE,2BAAmB;QACzB,cAAc,EAAE,IAAI;QACpB,IAAI,EAAE,CAAC,kBAAa,EAAE,eAAM,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,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;YAEtD,IAAI,IAAI,EAAE;gBACR,MAAM,EAAC,IAAI,EAAE,KAAK,EAAE,GAAG,YAAY,EAAC,GAAG,IAAI,CAAC;gBAC5C,IAAI,UAA2B,CAAC;gBAEhC,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,EAAE;oBACpC,MAAM,CAAC,KAAK,CAAC;wBACX,KAAK,EAAE,aAAa;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AEhC,OAAO,UAAU,CAAC;aACnB;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;AAnED,gEAmEC","sourcesContent":["import {setValue} from \"@tsed/core\";\nimport {Configuration, registerProvider, TokenProvider} from \"@tsed/di\";\nimport {Logger} from \"@tsed/logger\";\nimport Redis, {Cluster, RedisOptions} from \"ioredis\";\nimport {IORedisConfiguration} from \"../domain/IORedisConfiguration\";\nimport {ioRedisStore} from \"../domain/IORedisStore\";\n\nexport interface CreateConnectionProviderProps {\n provide: TokenProvider;\n name?: string;\n}\n\nexport const IOREDIS_CONNECTIONS = Symbol.for(\"ioredis:connections\");\nexport type IORedis = Redis & {name: string};\n\nexport function registerConnectionProvider({provide, name = \"default\"}: CreateConnectionProviderProps) {\n registerProvider({\n provide,\n type: IOREDIS_CONNECTIONS,\n connectionName: name,\n deps: [Configuration, Logger],\n async useAsyncFactory(configuration: Configuration, logger: Logger) {\n const items = configuration.get<IORedisConfiguration[]>(\"ioredis\", []);\n const item = items.find((item) => item.name === name);\n\n if (item) {\n const {name, cache, ...redisOptions} = item;\n let connection: Cluster | Redis;\n\n const reconnectOnError = (err: any) => {\n logger.fatal({\n event: \"REDIS_ERROR\",\n message: `Redis - Reconnect on error: ${(err && err.message) || err}`,\n stack: err?.stack\n });\n };\n\n if (\"nodes\" in redisOptions) {\n const {nodes, ...clusterOptions} = redisOptions;\n\n const clusterRetryStrategy = (times: number) => {\n logger.fatal({event: \"REDIS_ERROR\", message: `Redis is not responding - Retry count: ${times}`});\n return 2000;\n };\n\n setValue(clusterOptions, \"clusterRetryStrategy\", clusterRetryStrategy);\n setValue(clusterOptions, \"redisOptions.reconnectOnError\", reconnectOnError);\n\n connection = new Redis.Cluster(nodes, {\n ...clusterOptions,\n lazyConnect: true\n });\n } else {\n connection = new Redis({\n ...redisOptions,\n lazyConnect: true,\n reconnectOnError\n } as RedisOptions);\n }\n\n await connection.connect();\n\n logger.info(\"Connected to redis database...\");\n\n if (configuration.get(\"cache\") && cache) {\n configuration.set(\"cache.redisInstance\", connection);\n configuration.set(\"cache.store\", ioRedisStore);\n }\n\n (connection as any).name = name;\n\n return connection;\n }\n\n return {name};\n },\n hooks: {\n $onDestroy(connection: Redis) {\n return connection.disconnect && connection.disconnect();\n }\n }\n });\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IORedisConfiguration.js","sourceRoot":"","sources":["../../../src/domain/IORedisConfiguration.ts"],"names":[],"mappings":"","sourcesContent":["import {TokenProvider} from \"@tsed/di\";\nimport {ClusterOptions, RedisOptions} from \"ioredis\";\n\nexport type ClusterConfiguration = {nodes: string[]} & ClusterOptions;\n\nexport interface BaseIORedisConfiguration {\n name?: TokenProvider;\n cache?: boolean;\n}\n\nexport type IORedisConfiguration = BaseIORedisConfiguration & (RedisOptions | ClusterConfiguration);\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace TsED {\n interface Configuration {\n ioredis?: IORedisConfiguration[];\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import Redis from "ioredis";
|
|
2
|
+
async function handle(next, parse, cb) {
|
|
3
|
+
try {
|
|
4
|
+
let result = await next();
|
|
5
|
+
if (parse) {
|
|
6
|
+
result = result && JSON.parse(result);
|
|
7
|
+
}
|
|
8
|
+
if (!cb) {
|
|
9
|
+
return result;
|
|
10
|
+
}
|
|
11
|
+
cb(null, result);
|
|
12
|
+
}
|
|
13
|
+
catch (er) {
|
|
14
|
+
if (!cb) {
|
|
15
|
+
throw er;
|
|
16
|
+
}
|
|
17
|
+
cb(er, null);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export class IORedisStore {
|
|
21
|
+
name = "redis";
|
|
22
|
+
isCacheableValue;
|
|
23
|
+
redisCache;
|
|
24
|
+
storeArgs;
|
|
25
|
+
constructor(...args) {
|
|
26
|
+
if (args.length > 0 && args[0].redisInstance) {
|
|
27
|
+
this.redisCache = args[0].redisInstance;
|
|
28
|
+
}
|
|
29
|
+
else if (args.length > 0 && args[0].clusterConfig) {
|
|
30
|
+
const { nodes, options } = args[0].clusterConfig;
|
|
31
|
+
this.redisCache = new Redis.Cluster(nodes, options || {});
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
this.redisCache = new Redis(...args);
|
|
35
|
+
}
|
|
36
|
+
this.storeArgs = this.redisCache.options;
|
|
37
|
+
this.isCacheableValue = this.storeArgs.isCacheableValue || ((value) => value !== undefined && value !== null);
|
|
38
|
+
}
|
|
39
|
+
getClient() {
|
|
40
|
+
return this.redisCache;
|
|
41
|
+
}
|
|
42
|
+
set(key, value, options, cb) {
|
|
43
|
+
if (typeof options === "function") {
|
|
44
|
+
cb = options;
|
|
45
|
+
options = {};
|
|
46
|
+
}
|
|
47
|
+
options = options || {};
|
|
48
|
+
return handle(async () => {
|
|
49
|
+
if (!this.isCacheableValue(value)) {
|
|
50
|
+
throw new Error(`"${value}" is not a cacheable value`);
|
|
51
|
+
}
|
|
52
|
+
const ttl = options.ttl || options.ttl === 0 ? options.ttl : this.storeArgs.ttl;
|
|
53
|
+
const val = JSON.stringify(value) || '"undefined"';
|
|
54
|
+
if (ttl) {
|
|
55
|
+
return this.redisCache.setex(key, ttl, val);
|
|
56
|
+
}
|
|
57
|
+
return this.redisCache.set(key, val);
|
|
58
|
+
}, false, cb);
|
|
59
|
+
}
|
|
60
|
+
get(key, options, cb) {
|
|
61
|
+
if (typeof options === "function") {
|
|
62
|
+
cb = options;
|
|
63
|
+
}
|
|
64
|
+
return handle(() => this.redisCache.get(key), true, cb);
|
|
65
|
+
}
|
|
66
|
+
del(key, options, cb) {
|
|
67
|
+
if (typeof options === "function") {
|
|
68
|
+
cb = options;
|
|
69
|
+
}
|
|
70
|
+
return handle(() => this.redisCache.del(key), false, cb);
|
|
71
|
+
}
|
|
72
|
+
reset(cb) {
|
|
73
|
+
return handle(() => this.redisCache.flushdb(), false, cb);
|
|
74
|
+
}
|
|
75
|
+
keys(pattern, cb) {
|
|
76
|
+
if (typeof pattern === "function") {
|
|
77
|
+
cb = pattern;
|
|
78
|
+
pattern = "*";
|
|
79
|
+
}
|
|
80
|
+
return handle(() => this.redisCache.keys(pattern), false, cb);
|
|
81
|
+
}
|
|
82
|
+
ttl(key, cb) {
|
|
83
|
+
return handle(() => this.redisCache.ttl(key), false, cb);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export const ioRedisStore = { create: (...args) => new IORedisStore(...args) };
|
|
87
|
+
//# sourceMappingURL=IORedisStore.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IORedisStore.js","sourceRoot":"","sources":["../../../src/domain/IORedisStore.ts"],"names":[],"mappings":"AACA,OAAO,KAAgB,MAAM,SAAS,CAAC;AAGvC,KAAK,UAAU,MAAM,CAAiB,IAA6B,EAAE,KAAc,EAAE,EAA8B;IACjH,IAAI;QACF,IAAI,MAAM,GAAG,MAAM,IAAI,EAAE,CAAC;QAE1B,IAAI,KAAK,EAAE;YACT,MAAM,GAAG,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,MAAa,CAAC,CAAC;SAC9C;QAED,IAAI,CAAC,EAAE,EAAE;YACP,OAAO,MAAM,CAAC;SACf;QAED,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;KAClB;IAAC,OAAO,EAAE,EAAE;QACX,IAAI,CAAC,EAAE,EAAE;YACP,MAAM,EAAE,CAAC;SACV;QAED,EAAE,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;KACd;AACH,CAAC;AAED,MAAM,OAAO,YAAY;IAChB,IAAI,GAAG,OAAO,CAAC;IACf,gBAAgB,CAAC;IAChB,UAAU,CAAkB;IAC5B,SAAS,CAAM;I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AC1C,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;YACjC,EAAE,GAAG,OAAO,CAAC;YACb,OAAO,GAAG,GAAG,CAAC;SACf;QAED,OAAO,MAAM,CAAW,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;IAC1E,CAAC;IAED,GAAG,CAAC,GAAW,EAAE,EAAqB;QACpC,OAAO,MAAM,CAAS,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;IACnE,CAAC;CACF;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,EAAC,MAAM,EAAE,CAAC,GAAG,IAAW,EAAE,EAAE,CAAC,IAAI,YAAY,CAAC,GAAG,IAAI,CAAC,EAAC,CAAC","sourcesContent":["import {Store} from \"cache-manager\";\nimport Redis, {Cluster} from \"ioredis\";\nimport {Callback} from \"ioredis/built/types\";\n\nasync function handle<Response = any>(next: () => Promise<Response>, parse: boolean, cb?: Callback<Response | null>) {\n try {\n let result = await next();\n\n if (parse) {\n result = result && JSON.parse(result as any);\n }\n\n if (!cb) {\n return result;\n }\n\n cb(null, result);\n } catch (er) {\n if (!cb) {\n throw er;\n }\n\n cb(er, null);\n }\n}\n\nexport class IORedisStore implements Store {\n public name = \"redis\";\n public isCacheableValue;\n private redisCache: Redis | Cluster;\n private storeArgs: any;\n\n constructor(...args: any[]) {\n if (args.length > 0 && args[0].redisInstance) {\n this.redisCache = args[0].redisInstance;\n } else if (args.length > 0 && args[0].clusterConfig) {\n const {nodes, options} = args[0].clusterConfig;\n\n this.redisCache = new Redis.Cluster(nodes, options || {});\n } else {\n this.redisCache = new (Redis as any)(...args);\n }\n\n this.storeArgs = this.redisCache.options;\n this.isCacheableValue = this.storeArgs.isCacheableValue || ((value: any) => value !== undefined && value !== null);\n }\n\n getClient() {\n return this.redisCache;\n }\n\n set(key: string, value: any, options: any, cb?: Callback<\"OK\">) {\n if (typeof options === \"function\") {\n cb = options;\n options = {};\n }\n\n options = options || {};\n\n return handle<\"OK\">(\n async () => {\n if (!this.isCacheableValue(value)) {\n throw new Error(`\"${value}\" is not a cacheable value`);\n }\n\n const ttl = options.ttl || options.ttl === 0 ? options.ttl : this.storeArgs.ttl;\n const val = JSON.stringify(value) || '\"undefined\"';\n\n if (ttl) {\n return this.redisCache.setex(key, ttl, val);\n }\n\n return this.redisCache.set(key, val);\n },\n false,\n cb\n );\n }\n\n get(key: string, options?: any, cb?: Callback<string | null>) {\n if (typeof options === \"function\") {\n cb = options;\n }\n\n return handle(() => this.redisCache.get(key), true, cb);\n }\n\n del(key: string, options: any, cb?: Callback<number>) {\n if (typeof options === \"function\") {\n cb = options;\n }\n\n return handle(() => this.redisCache.del(key), false, cb);\n }\n\n reset(cb?: Callback<\"OK\">) {\n return handle(() => this.redisCache.flushdb(), false, cb);\n }\n\n keys(pattern: string, cb: Callback<string[]>) {\n if (typeof pattern === \"function\") {\n cb = pattern;\n pattern = \"*\";\n }\n\n return handle<string[]>(() => this.redisCache.keys(pattern), false, cb);\n }\n\n ttl(key: string, cb?: Callback<number>) {\n return handle<number>(() => this.redisCache.ttl(key), false, cb);\n }\n}\n\nexport const ioRedisStore = {create: (...args: any[]) => new IORedisStore(...args)};\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { DITest } from "@tsed/di";
|
|
2
|
+
import { mockConnections } from "../utils/mockConnections.js";
|
|
3
|
+
export class IORedisTest extends DITest {
|
|
4
|
+
static async create(options) {
|
|
5
|
+
const imports = mockConnections();
|
|
6
|
+
await Promise.all(imports.map(({ use }) => use.flushall()));
|
|
7
|
+
return DITest.create({
|
|
8
|
+
...IORedisTest.options,
|
|
9
|
+
...options,
|
|
10
|
+
imports: [...(options?.imports || []), ...imports]
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=IORedisTest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IORedisTest.js","sourceRoot":"","sources":["../../../src/domain/IORedisTest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,MAAM,EAAgB,MAAM,UAAU,CAAC;AAC/C,OAAO,EAAC,eAAe,EAAC,MAAM,0BAA0B,CAAC;AAEzD,MAAM,OAAO,WAAY,SAAQ,MAAM;IACrC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAuB;QACzC,MAAM,OAAO,GAAG,eAAe,EAAE,CAAC;QAElC,MAAM,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAE,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;QAE1D,OAAO,MAAM,CAAC,MAAM,CAAC;YACnB,GAAG,WAAW,CAAC,OAAO;YACtB,GAAG,OAAO;YACV,OAAO,EAAE,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,IAAI,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC;SACnD,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {DITest, DITestOptions} from \"@tsed/di\";\nimport {mockConnections} from \"../utils/mockConnections\";\n\nexport class IORedisTest extends DITest {\n static async create(options?: DITestOptions) {\n const imports = mockConnections();\n\n await Promise.all(imports.map(({use}) => use.flushall()));\n\n return DITest.create({\n ...IORedisTest.options,\n ...options,\n imports: [...(options?.imports || []), ...imports]\n });\n }\n}\n"]}
|
package/lib/esm/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Automatically generated by barrelsby.
|
|
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";
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,+BAA+B,CAAC;AAC9C,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,cAAc,oCAAoC,CAAC","sourcesContent":["/**\n * @file Automatically generated by barrelsby.\n */\n\nexport * from \"./domain/IORedisConfiguration\";\nexport * from \"./domain/IORedisStore\";\nexport * from \"./domain/IORedisTest\";\nexport * from \"./utils/mockConnections\";\nexport * from \"./utils/registerConnectionProvider\";\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { GlobalProviders } from "@tsed/di";
|
|
2
|
+
import RealIORedis from "ioredis-mock";
|
|
3
|
+
import { IOREDIS_CONNECTIONS } from "./registerConnectionProvider.js";
|
|
4
|
+
export function mockConnection(token, name) {
|
|
5
|
+
const connection = new RealIORedis();
|
|
6
|
+
connection.name = name;
|
|
7
|
+
return {
|
|
8
|
+
token,
|
|
9
|
+
use: connection
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export function mockConnections() {
|
|
13
|
+
return [...GlobalProviders.values()]
|
|
14
|
+
.filter((provider) => provider.type === IOREDIS_CONNECTIONS)
|
|
15
|
+
.map((provider) => mockConnection(provider.token, provider.connectionName));
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=mockConnections.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mockConnections.js","sourceRoot":"","sources":["../../../src/utils/mockConnections.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAgB,MAAM,UAAU,CAAC;AAExD,OAAO,WAAW,MAAM,cAAc,CAAC;AACvC,OAAO,EAAC,mBAAmB,EAAC,MAAM,8BAA8B,CAAC;AAEjE,MAAM,UAAU,cAAc,CAAC,KAAoB,EAAE,IAAY;IAC/D,MAAM,UAAU,GAAU,IAAK,WAAmB,EAAE,CAAC;IAEpD,UAAkB,CAAC,IAAI,GAAG,IAAI,CAAC;IAEhC,OAAO;QACL,KAAK;QACL,GAAG,EAAE,UAAU;KAChB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,eAAe;IAC7B,OAAO,CAAC,GAAG,eAAe,CAAC,MAAM,EAAE,CAAC;SACjC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,KAAK,mBAAmB,CAAC;SAC3D,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,cAAc,CAAC,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import {GlobalProviders, TokenProvider} from \"@tsed/di\";\nimport Redis from \"ioredis\";\nimport RealIORedis from \"ioredis-mock\";\nimport {IOREDIS_CONNECTIONS} from \"./registerConnectionProvider\";\n\nexport function mockConnection(token: TokenProvider, name: string) {\n const connection: Redis = new (RealIORedis as any)();\n\n (connection as any).name = name;\n\n return {\n token,\n use: connection\n };\n}\n\nexport function mockConnections() {\n return [...GlobalProviders.values()]\n .filter((provider) => provider.type === IOREDIS_CONNECTIONS)\n .map((provider) => mockConnection(provider.token, provider.connectionName));\n}\n"]}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { setValue } from "@tsed/core";
|
|
2
|
+
import { Configuration, registerProvider } from "@tsed/di";
|
|
3
|
+
import { Logger } from "@tsed/logger";
|
|
4
|
+
import Redis from "ioredis";
|
|
5
|
+
import { ioRedisStore } from "../domain/IORedisStore.js";
|
|
6
|
+
export const IOREDIS_CONNECTIONS = Symbol.for("ioredis:connections");
|
|
7
|
+
export function registerConnectionProvider({ provide, name = "default" }) {
|
|
8
|
+
registerProvider({
|
|
9
|
+
provide,
|
|
10
|
+
type: IOREDIS_CONNECTIONS,
|
|
11
|
+
connectionName: name,
|
|
12
|
+
deps: [Configuration, Logger],
|
|
13
|
+
async useAsyncFactory(configuration, logger) {
|
|
14
|
+
const items = configuration.get("ioredis", []);
|
|
15
|
+
const item = items.find((item) => item.name === name);
|
|
16
|
+
if (item) {
|
|
17
|
+
const { name, cache, ...redisOptions } = item;
|
|
18
|
+
let connection;
|
|
19
|
+
const reconnectOnError = (err) => {
|
|
20
|
+
logger.fatal({
|
|
21
|
+
event: "REDIS_ERROR",
|
|
22
|
+
message: `Redis - Reconnect on error: ${(err && err.message) || err}`,
|
|
23
|
+
stack: err?.stack
|
|
24
|
+
});
|
|
25
|
+
};
|
|
26
|
+
if ("nodes" in redisOptions) {
|
|
27
|
+
const { nodes, ...clusterOptions } = redisOptions;
|
|
28
|
+
const clusterRetryStrategy = (times) => {
|
|
29
|
+
logger.fatal({ event: "REDIS_ERROR", message: `Redis is not responding - Retry count: ${times}` });
|
|
30
|
+
return 2000;
|
|
31
|
+
};
|
|
32
|
+
setValue(clusterOptions, "clusterRetryStrategy", clusterRetryStrategy);
|
|
33
|
+
setValue(clusterOptions, "redisOptions.reconnectOnError", reconnectOnError);
|
|
34
|
+
connection = new Redis.Cluster(nodes, {
|
|
35
|
+
...clusterOptions,
|
|
36
|
+
lazyConnect: true
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
connection = new Redis({
|
|
41
|
+
...redisOptions,
|
|
42
|
+
lazyConnect: true,
|
|
43
|
+
reconnectOnError
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
await connection.connect();
|
|
47
|
+
logger.info("Connected to redis database...");
|
|
48
|
+
if (configuration.get("cache") && cache) {
|
|
49
|
+
configuration.set("cache.redisInstance", connection);
|
|
50
|
+
configuration.set("cache.store", ioRedisStore);
|
|
51
|
+
}
|
|
52
|
+
connection.name = name;
|
|
53
|
+
return connection;
|
|
54
|
+
}
|
|
55
|
+
return { name };
|
|
56
|
+
},
|
|
57
|
+
hooks: {
|
|
58
|
+
$onDestroy(connection) {
|
|
59
|
+
return connection.disconnect && connection.disconnect();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
//# sourceMappingURL=registerConnectionProvider.js.map
|
|
@@ -0,0 +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;AACpC,OAAO,KAA8B,MAAM,SAAS,CAAC;AAErD,OAAO,EAAC,YAAY,EAAC,MAAM,wBAAwB,CAAC;AAOpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAGrE,MAAM,UAAU,0BAA0B,CAAC,EAAC,OAAO,EAAE,IAAI,GAAG,SAAS,EAAgC;IACnG,gBAAgB,CAAC;QACf,OAAO;QACP,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,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;YAEtD,IAAI,IAAI,EAAE;gBACR,MAAM,EAAC,IAAI,EAAE,KAAK,EAAE,GAAG,YAAY,EAAC,GAAG,IAAI,CAAC;gBAC5C,IAAI,UAA2B,CAAC;gBAEhC,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE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gBAEA,UAAkB,CAAC,IAAI,GAAG,IAAI,CAAC;gBAEhC,OAAO,UAAU,CAAC;aACnB;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","sourcesContent":["import {setValue} from \"@tsed/core\";\nimport {Configuration, registerProvider, TokenProvider} from \"@tsed/di\";\nimport {Logger} from \"@tsed/logger\";\nimport Redis, {Cluster, RedisOptions} from \"ioredis\";\nimport {IORedisConfiguration} from \"../domain/IORedisConfiguration\";\nimport {ioRedisStore} from \"../domain/IORedisStore\";\n\nexport interface CreateConnectionProviderProps {\n provide: TokenProvider;\n name?: string;\n}\n\nexport const IOREDIS_CONNECTIONS = Symbol.for(\"ioredis:connections\");\nexport type IORedis = Redis & {name: string};\n\nexport function registerConnectionProvider({provide, name = \"default\"}: CreateConnectionProviderProps) {\n registerProvider({\n provide,\n type: IOREDIS_CONNECTIONS,\n connectionName: name,\n deps: [Configuration, Logger],\n async useAsyncFactory(configuration: Configuration, logger: Logger) {\n const items = configuration.get<IORedisConfiguration[]>(\"ioredis\", []);\n const item = items.find((item) => item.name === name);\n\n if (item) {\n const {name, cache, ...redisOptions} = item;\n let connection: Cluster | Redis;\n\n const reconnectOnError = (err: any) => {\n logger.fatal({\n event: \"REDIS_ERROR\",\n message: `Redis - Reconnect on error: ${(err && err.message) || err}`,\n stack: err?.stack\n });\n };\n\n if (\"nodes\" in redisOptions) {\n const {nodes, ...clusterOptions} = redisOptions;\n\n const clusterRetryStrategy = (times: number) => {\n logger.fatal({event: \"REDIS_ERROR\", message: `Redis is not responding - Retry count: ${times}`});\n return 2000;\n };\n\n setValue(clusterOptions, \"clusterRetryStrategy\", clusterRetryStrategy);\n setValue(clusterOptions, \"redisOptions.reconnectOnError\", reconnectOnError);\n\n connection = new Redis.Cluster(nodes, {\n ...clusterOptions,\n lazyConnect: true\n });\n } else {\n connection = new Redis({\n ...redisOptions,\n lazyConnect: true,\n reconnectOnError\n } as RedisOptions);\n }\n\n await connection.connect();\n\n logger.info(\"Connected to redis database...\");\n\n if (configuration.get(\"cache\") && cache) {\n configuration.set(\"cache.redisInstance\", connection);\n configuration.set(\"cache.store\", ioRedisStore);\n }\n\n (connection as any).name = name;\n\n return connection;\n }\n\n return {name};\n },\n hooks: {\n $onDestroy(connection: Redis) {\n return connection.disconnect && connection.disconnect();\n }\n }\n });\n}\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { TokenProvider } from "@tsed/di";
|
|
2
|
+
import { ClusterOptions, RedisOptions } from "ioredis";
|
|
3
|
+
export declare type ClusterConfiguration = {
|
|
4
|
+
nodes: string[];
|
|
5
|
+
} & ClusterOptions;
|
|
6
|
+
export interface BaseIORedisConfiguration {
|
|
7
|
+
name?: TokenProvider;
|
|
8
|
+
cache?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare type IORedisConfiguration = BaseIORedisConfiguration & (RedisOptions | ClusterConfiguration);
|
|
11
|
+
declare global {
|
|
12
|
+
namespace TsED {
|
|
13
|
+
interface Configuration {
|
|
14
|
+
ioredis?: IORedisConfiguration[];
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Store } from "cache-manager";
|
|
2
|
+
import Redis, { Cluster } from "ioredis";
|
|
3
|
+
import { Callback } from "ioredis/built/types";
|
|
4
|
+
export declare class IORedisStore implements Store {
|
|
5
|
+
name: string;
|
|
6
|
+
isCacheableValue: any;
|
|
7
|
+
private redisCache;
|
|
8
|
+
private storeArgs;
|
|
9
|
+
constructor(...args: any[]);
|
|
10
|
+
getClient(): Redis | Cluster;
|
|
11
|
+
set(key: string, value: any, options: any, cb?: Callback<"OK">): Promise<"OK" | undefined>;
|
|
12
|
+
get(key: string, options?: any, cb?: Callback<string | null>): Promise<string | null | undefined>;
|
|
13
|
+
del(key: string, options: any, cb?: Callback<number>): Promise<number | undefined>;
|
|
14
|
+
reset(cb?: Callback<"OK">): Promise<"OK" | undefined>;
|
|
15
|
+
keys(pattern: string, cb: Callback<string[]>): Promise<string[] | undefined>;
|
|
16
|
+
ttl(key: string, cb?: Callback<number>): Promise<number | undefined>;
|
|
17
|
+
}
|
|
18
|
+
export declare const ioRedisStore: {
|
|
19
|
+
create: (...args: any[]) => IORedisStore;
|
|
20
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Automatically generated by barrelsby.
|
|
3
|
+
*/
|
|
4
|
+
export * from "./domain/IORedisConfiguration";
|
|
5
|
+
export * from "./domain/IORedisStore";
|
|
6
|
+
export * from "./domain/IORedisTest";
|
|
7
|
+
export * from "./utils/mockConnections";
|
|
8
|
+
export * from "./utils/registerConnectionProvider";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { TokenProvider } from "@tsed/di";
|
|
2
|
+
import Redis from "ioredis";
|
|
3
|
+
export declare function mockConnection(token: TokenProvider, name: string): {
|
|
4
|
+
token: any;
|
|
5
|
+
use: Redis;
|
|
6
|
+
};
|
|
7
|
+
export declare function mockConnections(): {
|
|
8
|
+
token: any;
|
|
9
|
+
use: Redis;
|
|
10
|
+
}[];
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { TokenProvider } from "@tsed/di";
|
|
2
|
+
import Redis from "ioredis";
|
|
3
|
+
export interface CreateConnectionProviderProps {
|
|
4
|
+
provide: TokenProvider;
|
|
5
|
+
name?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare const IOREDIS_CONNECTIONS: unique symbol;
|
|
8
|
+
export declare type IORedis = Redis & {
|
|
9
|
+
name: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function registerConnectionProvider({ provide, name }: CreateConnectionProviderProps): void;
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tsed/ioredis",
|
|
3
|
+
"version": "6.129.0",
|
|
4
|
+
"description": "IO Redis connection for Ts.ED",
|
|
5
|
+
"private": false,
|
|
6
|
+
"source": "./src/index.ts",
|
|
7
|
+
"main": "./lib/cjs/index.js",
|
|
8
|
+
"module": "./lib/esm/index.js",
|
|
9
|
+
"typings": "./lib/types/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
"types": "./lib/types/index.d.ts",
|
|
12
|
+
"import": "./lib/esm/index.js",
|
|
13
|
+
"require": "./lib/cjs/index.js",
|
|
14
|
+
"default": "./lib/esm/index.js"
|
|
15
|
+
},
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "yarn barrels && yarn run build:esm && yarn run build:cjs",
|
|
18
|
+
"build:cjs": "tsc --build tsconfig.compile.json",
|
|
19
|
+
"build:esm": "tsc --build tsconfig.compile.esm.json",
|
|
20
|
+
"barrels": "yarn barrelsby --delete -d ./src -e \"\\.spec\\.ts\" -e \"__mock__\" -e \".benchmark.ts\"",
|
|
21
|
+
"test": "cross-env NODE_ENV=test yarn jest"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"tslib": "2.4.0"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@tsed/core": "6.129.0",
|
|
28
|
+
"@tsed/di": "6.129.0",
|
|
29
|
+
"@types/ioredis-mock": "^5.6.0",
|
|
30
|
+
"ioredis": "5.2.3",
|
|
31
|
+
"ioredis-mock": "8.2.2"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@tsed/core": "^6.129.0",
|
|
35
|
+
"@tsed/di": "^6.129.0",
|
|
36
|
+
"ioredis": ">=5.2.3",
|
|
37
|
+
"ioredis-mock": ">=8.2.2"
|
|
38
|
+
},
|
|
39
|
+
"repository": "https://github.com/tsedio/tsed",
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/tsedio/tsed/issues"
|
|
42
|
+
},
|
|
43
|
+
"homepage": "https://github.com/tsedio/tsed/tree/production/packages/orm/ioredis",
|
|
44
|
+
"author": "Romain Lenzotti",
|
|
45
|
+
"license": "MIT"
|
|
46
|
+
}
|
package/readme.md
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
<p style="text-align: center" align="center">
|
|
2
|
+
<a href="https://tsed.io" target="_blank"><img src="https://tsed.io/tsed-og.png" width="200" alt="Ts.ED logo"/></a>
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<div align="center">
|
|
6
|
+
<h1>@tsed/ioredis</h1>
|
|
7
|
+
|
|
8
|
+
[](https://github.com/tsedio/tsed/actions?query=workflow%3A%22Build+%26+Release%22)
|
|
9
|
+
[](https://github.com/tsedio/tsed/blob/master/CONTRIBUTING.md)
|
|
10
|
+
[](https://coveralls.io/github/tsedio/tsed?branch=production)
|
|
11
|
+
[](https://badge.fury.io/js/%40tsed%2Fcommon)
|
|
12
|
+
[](https://github.com/semantic-release/semantic-release)
|
|
13
|
+
[](https://github.com/prettier/prettier)
|
|
14
|
+
[](https://github.com/sponsors/romakita)
|
|
15
|
+
[](https://opencollective.com/tsed)
|
|
16
|
+
|
|
17
|
+
</div>
|
|
18
|
+
|
|
19
|
+
<div align="center">
|
|
20
|
+
<a href="https://tsed.io/">Website</a>
|
|
21
|
+
<span> • </span>
|
|
22
|
+
<a href="https://tsed.io/getting-started/">Getting started</a>
|
|
23
|
+
<span> • </span>
|
|
24
|
+
<a href="https://api.tsed.io/rest/slack/tsedio/tsed">Slack</a>
|
|
25
|
+
<span> • </span>
|
|
26
|
+
<a href="https://twitter.com/TsED_io">Twitter</a>
|
|
27
|
+
</div>
|
|
28
|
+
|
|
29
|
+
<hr />
|
|
30
|
+
|
|
31
|
+
A package of Ts.ED framework. See website: https://tsed.io/tutorials/redis.html
|
|
32
|
+
|
|
33
|
+
## Features
|
|
34
|
+
|
|
35
|
+
Currently, `@tsed/ioredis` allows you:
|
|
36
|
+
|
|
37
|
+
- Configure one or more Redis database connections via the `@Configuration` configuration.
|
|
38
|
+
- Share redis connection with `@tsed/platform-cache`.
|
|
39
|
+
- Support classic Redis connection and Cluster connection.
|
|
40
|
+
- Inject connection to another service.
|
|
41
|
+
- Mock connection for unit/integration test.
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
```shell
|
|
46
|
+
npm install --save @tsed/ioredis ioredis ioredis-mock
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
> Minimal supported ioredis version is v5+
|
|
50
|
+
|
|
51
|
+
## Create connection
|
|
52
|
+
|
|
53
|
+
Create a new `RedisConnection.ts` file in your project:
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
import Redis from "ioredis";
|
|
57
|
+
import {registerConnectionProvider} from "@tsed/ioredis";
|
|
58
|
+
|
|
59
|
+
export const REDIS_CONNECTION = Symbol.for("REDIS_CONNECTION");
|
|
60
|
+
export type REDIS_CONNECTION = Redis;
|
|
61
|
+
|
|
62
|
+
registerConnectionProvider({
|
|
63
|
+
provide: REDIS_CONNECTION,
|
|
64
|
+
name: "default"
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
> registerConnectionProvider create automatically an injectable RedisConnection
|
|
69
|
+
|
|
70
|
+
Then, edit your `Server.ts`:
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
import {Configuration} from "@tsed/di";
|
|
74
|
+
import "@tsed/platform-cache"; // add this module if you want to use cache
|
|
75
|
+
import "@tsed/ioredis";
|
|
76
|
+
|
|
77
|
+
@Configuration({
|
|
78
|
+
ioredis: [
|
|
79
|
+
{
|
|
80
|
+
name: "default",
|
|
81
|
+
// share the redis connection with @tsed/platform-cache
|
|
82
|
+
cache: true
|
|
83
|
+
|
|
84
|
+
// redis options
|
|
85
|
+
// host: "localhost",
|
|
86
|
+
// port: 6379,
|
|
87
|
+
// username: "...",
|
|
88
|
+
// password: "...",
|
|
89
|
+
// tls: false,
|
|
90
|
+
// db: 0
|
|
91
|
+
}
|
|
92
|
+
],
|
|
93
|
+
// cache options
|
|
94
|
+
cache: {
|
|
95
|
+
ttl: 300
|
|
96
|
+
}
|
|
97
|
+
})
|
|
98
|
+
class MyModule {}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
And finally, use the connection in your services:
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
import {Injectable} from "@tsed/di";
|
|
105
|
+
|
|
106
|
+
@Injectable()
|
|
107
|
+
export class ClientRepository {
|
|
108
|
+
@Inject(REDIS_CONNECTION)
|
|
109
|
+
protected connection: REDIS_CONNECTION; // ioredis instance
|
|
110
|
+
|
|
111
|
+
async keys() {
|
|
112
|
+
return this.connection.keys("clients:*");
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
> See [ioredis documentation](https://github.com/luin/ioredis) for more details.
|
|
118
|
+
|
|
119
|
+
## Cluster configuration
|
|
120
|
+
|
|
121
|
+
```typescript
|
|
122
|
+
import {Configuration} from "@tsed/di";
|
|
123
|
+
import "@tsed/platform-cache"; // add this module if you want to use cache
|
|
124
|
+
import "@tsed/ioredis";
|
|
125
|
+
|
|
126
|
+
@Configuration({
|
|
127
|
+
ioredis: [
|
|
128
|
+
{
|
|
129
|
+
name: "default",
|
|
130
|
+
// share the redis connection with @tsed/platform-cache
|
|
131
|
+
cache: true,
|
|
132
|
+
// cluster options
|
|
133
|
+
nodes: ["..."],
|
|
134
|
+
// other cluster options
|
|
135
|
+
scaleReads: "all",
|
|
136
|
+
maxRedirections: 16,
|
|
137
|
+
retryDelayOnTryAgain: 100,
|
|
138
|
+
retryDelayOnFailover: 200,
|
|
139
|
+
retryDelayOnClusterDown: 1000,
|
|
140
|
+
slotsRefreshTimeout: 15000,
|
|
141
|
+
slotsRefreshInterval: 20000,
|
|
142
|
+
enableOfflineQueue: true,
|
|
143
|
+
enableReadyCheck: true,
|
|
144
|
+
redisOptions: {
|
|
145
|
+
noDelay: true,
|
|
146
|
+
connectTimeout: 15000,
|
|
147
|
+
autoResendUnfulfilledCommands: true,
|
|
148
|
+
maxRetriesPerRequest: 5,
|
|
149
|
+
enableAutoPipelining: true,
|
|
150
|
+
autoPipeliningIgnoredCommands: ["scan"]
|
|
151
|
+
}
|
|
152
|
+
//
|
|
153
|
+
}
|
|
154
|
+
],
|
|
155
|
+
// cache options
|
|
156
|
+
cache: {
|
|
157
|
+
ttl: 300
|
|
158
|
+
}
|
|
159
|
+
})
|
|
160
|
+
class MyModule {}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Testing
|
|
164
|
+
|
|
165
|
+
Ts.ED provides a utility that allows you to test a service that consumes a Redis connection.
|
|
166
|
+
This use relies on the awesome [ioredis-mock](https://www.npmjs.com/package/ioredis-mock) module.
|
|
167
|
+
|
|
168
|
+
Here is a class that consume a redis connection:
|
|
169
|
+
|
|
170
|
+
```typescript
|
|
171
|
+
import {v4} from "uuid";
|
|
172
|
+
import {Injectable} from "@tsed/di";
|
|
173
|
+
import {serialize, deserialize} from "@tsed/json-mapper";
|
|
174
|
+
import {REDIS_CONNECTION} from "./RedisConnection";
|
|
175
|
+
import {ClientModel} from "./ClientModel";
|
|
176
|
+
|
|
177
|
+
@Injectable()
|
|
178
|
+
export class ClientRepository {
|
|
179
|
+
@Inject(REDIS_CONNECTION)
|
|
180
|
+
protected connection: REDIS_CONNECTION; // ioredis instance
|
|
181
|
+
|
|
182
|
+
async get(id: string) {
|
|
183
|
+
const raw = await this.connection.get("clients:" + id);
|
|
184
|
+
|
|
185
|
+
if (!raw) {
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return deserialize(JSON.parse(raw), {type: ClientModel});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async save(client: ClientModel) {
|
|
193
|
+
client.id = client.id || v4();
|
|
194
|
+
|
|
195
|
+
this.connection.set("clients:" + client.id, JSON.stringify(serialize(client)));
|
|
196
|
+
|
|
197
|
+
return client;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
The ClientModel:
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
import {Schema} from "@tsed/schema";
|
|
206
|
+
|
|
207
|
+
export class ClientModel {
|
|
208
|
+
@Property()
|
|
209
|
+
id: string;
|
|
210
|
+
|
|
211
|
+
@Property()
|
|
212
|
+
name: string;
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
And his test:
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
import {ClientRepository} from "./ClientRepository";
|
|
220
|
+
import {REDIS_CONNECTION} from "./RedisConnection";
|
|
221
|
+
import {ClientModel} from "./ClientModel";
|
|
222
|
+
|
|
223
|
+
describe("IORedisTest", () => {
|
|
224
|
+
beforeEach(() => IORedisTest.create()); // create a new sandbox with ioredis-mock connection
|
|
225
|
+
afterEach(() => IORedisTest.reset());
|
|
226
|
+
|
|
227
|
+
it("should return nothing", async () => {
|
|
228
|
+
const service = IORedisTest.get<MyRepository>(MyRepository);
|
|
229
|
+
|
|
230
|
+
const client = await service.get("uid");
|
|
231
|
+
|
|
232
|
+
expect(client).toEqual(undefined);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it("should return all keys", async () => {
|
|
236
|
+
const service = IORedisTest.get<MyRepository>(MyRepository);
|
|
237
|
+
const client = new ClientModel();
|
|
238
|
+
client.name = "name";
|
|
239
|
+
|
|
240
|
+
const newClient = await service.save(client);
|
|
241
|
+
|
|
242
|
+
expect(newClient.id).toBeInstanceOf(String);
|
|
243
|
+
expect(newClient.name).toEqual("name");
|
|
244
|
+
|
|
245
|
+
const clientFound = await service.get(newClient.id);
|
|
246
|
+
|
|
247
|
+
expect(clientFound).toBeInstanceOf(ClientModel);
|
|
248
|
+
expect(clientFound.id).toEqual(newClient.id);
|
|
249
|
+
expect(clientFound.name).toEqual("name");
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
## Contributors
|
|
255
|
+
|
|
256
|
+
Please read [contributing guidelines here](https://tsed.io/CONTRIBUTING.html)
|
|
257
|
+
|
|
258
|
+
<a href="https://github.com/tsedio/ts-express-decorators/graphs/contributors"><img src="https://opencollective.com/tsed/contributors.svg?width=890" /></a>
|
|
259
|
+
|
|
260
|
+
## Backers
|
|
261
|
+
|
|
262
|
+
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/tsed#backer)]
|
|
263
|
+
|
|
264
|
+
<a href="https://opencollective.com/tsed#backers" target="_blank"><img src="https://opencollective.com/tsed/backers.svg?width=890"></a>
|
|
265
|
+
|
|
266
|
+
## Sponsors
|
|
267
|
+
|
|
268
|
+
Support this project by becoming a sponsor. Your logo will show up here with a link to your
|
|
269
|
+
website. [[Become a sponsor](https://opencollective.com/tsed#sponsor)]
|
|
270
|
+
|
|
271
|
+
## License
|
|
272
|
+
|
|
273
|
+
The MIT License (MIT)
|
|
274
|
+
|
|
275
|
+
Copyright (c) 2016 - 2022 Romain Lenzotti
|
|
276
|
+
|
|
277
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
|
278
|
+
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
|
|
279
|
+
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
|
|
280
|
+
persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
281
|
+
|
|
282
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
|
283
|
+
Software.
|
|
284
|
+
|
|
285
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
|
286
|
+
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
287
|
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
288
|
+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "./tsconfig.compile.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"baseUrl": ".",
|
|
5
|
+
"module": "ES2020",
|
|
6
|
+
"rootDir": "src",
|
|
7
|
+
"outDir": "./lib/esm",
|
|
8
|
+
"declaration": true,
|
|
9
|
+
"declarationDir": "./lib/types"
|
|
10
|
+
},
|
|
11
|
+
"exclude": ["node_modules", "test", "lib", "benchmark", "coverage", "spec", "**/*.benchmark.ts", "**/*.spec.ts", "keys", "jest.config.js"]
|
|
12
|
+
}
|