@optimiser/common 1.0.365 → 1.0.367

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.
Files changed (69) hide show
  1. package/dist/aws/awsservices.d.ts +39 -39
  2. package/dist/aws/awsservices.js +398 -398
  3. package/dist/constants.d.ts +35 -35
  4. package/dist/constants.js +36 -36
  5. package/dist/enums/databasetype.enum.d.ts +7 -7
  6. package/dist/enums/databasetype.enum.js +11 -11
  7. package/dist/enums/log.enum.d.ts +22 -22
  8. package/dist/enums/log.enum.js +26 -26
  9. package/dist/index.d.ts +25 -25
  10. package/dist/index.js +69 -61
  11. package/dist/lib/activity.d.ts +1 -1
  12. package/dist/lib/activity.js +44 -44
  13. package/dist/lib/calculatedbsize.d.ts +15 -15
  14. package/dist/lib/calculatedbsize.js +75 -75
  15. package/dist/lib/connection.d.ts +116 -116
  16. package/dist/lib/connection.js +595 -595
  17. package/dist/lib/convertfilesize.d.ts +2 -2
  18. package/dist/lib/convertfilesize.js +15 -15
  19. package/dist/lib/countrycode.d.ts +2 -2
  20. package/dist/lib/countrycode.js +255 -255
  21. package/dist/lib/event.d.ts +26 -26
  22. package/dist/lib/event.js +252 -248
  23. package/dist/lib/helper.d.ts +94 -93
  24. package/dist/lib/helper.js +1016 -1009
  25. package/dist/lib/memoryserverclient.d.ts +40 -40
  26. package/dist/lib/memoryserverclient.js +256 -252
  27. package/dist/lib/operautilitycommon.d.ts +65 -65
  28. package/dist/lib/operautilitycommon.js +620 -620
  29. package/dist/lib/redis.d.ts +21 -21
  30. package/dist/lib/redis.js +46 -46
  31. package/dist/lib/socketidfromredis.d.ts +3 -3
  32. package/dist/lib/socketidfromredis.js +5 -5
  33. package/dist/lib/taskutils.d.ts +40 -40
  34. package/dist/lib/taskutils.js +656 -656
  35. package/dist/lib/utility.d.ts +300 -298
  36. package/dist/lib/utility.js +5626 -5621
  37. package/dist/lib/validateRequest.d.ts +3 -3
  38. package/dist/lib/validateRequest.js +13 -13
  39. package/dist/logs/auditlog.d.ts +25 -25
  40. package/dist/logs/auditlog.js +1033 -1029
  41. package/dist/logs/checklogtable.d.ts +3 -3
  42. package/dist/logs/checklogtable.js +67 -67
  43. package/dist/logs/log.table.d.ts +7 -7
  44. package/dist/logs/log.table.js +127 -127
  45. package/dist/modals/connection.modal.d.ts +32 -32
  46. package/dist/modals/connection.modal.js +2 -2
  47. package/dist/modals/globalNotification.modal.d.ts +8 -8
  48. package/dist/modals/globalNotification.modal.js +2 -2
  49. package/dist/modals/log.modal.d.ts +64 -64
  50. package/dist/modals/log.modal.js +2 -2
  51. package/dist/modals/mail.modal.d.ts +6 -6
  52. package/dist/modals/mail.modal.js +2 -2
  53. package/dist/modals/notificationData.modal.d.ts +29 -29
  54. package/dist/modals/notificationData.modal.js +2 -2
  55. package/dist/modals/redisconfig.modal.d.ts +6 -6
  56. package/dist/modals/redisconfig.modal.js +2 -2
  57. package/dist/modals/sqsconfig.modal.d.ts +8 -8
  58. package/dist/modals/sqsconfig.modal.js +2 -2
  59. package/dist/modals/utility.modal.d.ts +17 -17
  60. package/dist/modals/utility.modal.js +2 -2
  61. package/dist/utility/crypto.d.ts +4 -4
  62. package/dist/utility/crypto.js +43 -43
  63. package/dist/utility/errorHandler.d.ts +30 -30
  64. package/dist/utility/errorHandler.js +24 -24
  65. package/dist/utility/errorHandlerForServices.d.ts +22 -22
  66. package/dist/utility/errorHandlerForServices.js +19 -19
  67. package/dist/utility/mail.d.ts +21 -21
  68. package/dist/utility/mail.js +91 -87
  69. package/package.json +3 -3
@@ -1,595 +1,595 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (_) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __importDefault = (this && this.__importDefault) || function (mod) {
39
- return (mod && mod.__esModule) ? mod : { "default": mod };
40
- };
41
- Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.Connection = void 0;
43
- var mongodb_1 = require("mongodb");
44
- var sequelize_1 = require("sequelize");
45
- var errorHandler_1 = __importDefault(require("../utility/errorHandler"));
46
- var mail_1 = require("../utility/mail");
47
- var Connection = /** @class */ (function () {
48
- /**
49
- * @param masterConfig Master Connectivity Object
50
- * @param redisClient Redisclient
51
- * @description connect to master database and maintain master config and redis client for furture ref
52
- */
53
- function Connection(masterConfig, redisClient) {
54
- var _this = this;
55
- this.masterConfig = masterConfig;
56
- this.redisClient = redisClient;
57
- this.connections = {};
58
- /**
59
- *
60
- * @param req
61
- * @param res
62
- * @param next
63
- * @description middleware function : create database connection if not present
64
- */
65
- this.DbConnection = function (req, res, next) {
66
- if (!req.DBName || !req.DBAddress) {
67
- next("Dbname or DbAddress not defined");
68
- }
69
- else if (!_this.connections[Buffer.from(req.DBAddress).toString('base64')]) {
70
- _this.ConnectToDb({
71
- DBName: req.DBName,
72
- DBAddress: req.DBAddress
73
- }, next).then(function () {
74
- next();
75
- });
76
- }
77
- else {
78
- next();
79
- }
80
- };
81
- /**
82
- *
83
- * @param req
84
- * @param res
85
- * @param next
86
- * @description middleware function : to validate the cookies that are passed in request
87
- */
88
- this.ValidateSession = function (req, res, next) {
89
- // If the header 'x-access-token' exists, override the req.cookies.msp_d.token
90
- if (req.headers['x-access-token']) {
91
- if (!req.cookies)
92
- req.cookies = {};
93
- if (!req.cookies.msp_d)
94
- req.cookies.msp_d = {};
95
- req.cookies.msp_d.token = req.headers['x-access-token'];
96
- }
97
- if (req.cookies && req.cookies.msp_d && _this.redisClient) {
98
- _this.redisClient.hgetall(req.cookies.msp_d.token, function (err, tokenData) {
99
- if (tokenData === undefined || tokenData === null || Object.keys(tokenData).length == 0) {
100
- req.cookies.msp_d = tokenData; /* Now no need to keep ui/upi/ci on client side. */
101
- var masterObj = {
102
- DBName: _this.masterConfig.MASTER_DB_NAME,
103
- DBAddress: _this.masterConfig.MASTER_CONNECTION_STRING,
104
- };
105
- if (_this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]) {
106
- _this.SendErrorResponse(req, res);
107
- }
108
- else {
109
- _this.ConnectToDb(masterObj, next).then(function () {
110
- _this.SendErrorResponse(req, res);
111
- });
112
- }
113
- }
114
- else {
115
- req.cookies.msp_d = tokenData; /* Now no need to keep ui/upi/ci on client side. */
116
- req["DBName"] = tokenData.DBName;
117
- req["StorageType"] = tokenData.StorageType;
118
- req["DBAddress"] = tokenData.DBAddress;
119
- req["StorageSettings"] = JSON.parse(tokenData.StorageSettings);
120
- if ((parseInt(tokenData.TimeOut) > 0) && _this.redisClient) {
121
- _this.redisClient.expire((req.cookies.msp_d.token).toString(), parseInt(tokenData.TimeOut));
122
- }
123
- next();
124
- }
125
- });
126
- }
127
- else if (req.headers['is-system'] && req.headers['system-token'] && req.headers['system-type'] && _this.redisClient) {
128
- /** TODO::
129
- * Validate Session from Redis
130
- * Update system type in redisClient
131
- */
132
- _this.redisClient.hgetall((req.headers['system-token']).toString(), function (err, systemTokenData) {
133
- if (systemTokenData === undefined || systemTokenData === null || Object.keys(systemTokenData).length == 0) {
134
- /* Token not Validated. */
135
- return res.json({
136
- statusCode: 401,
137
- message: "Not Authorized.",
138
- data: {}
139
- });
140
- }
141
- else {
142
- /* Validated. */
143
- if (req.headers['db-name'] && req.headers['db-address']) {
144
- req["DBName"] = (req.headers['db-name']).toString();
145
- req["DBAddress"] = (req.headers['db-address']).toString();
146
- next();
147
- }
148
- else {
149
- /* DBName / DBAddress is not provided. */
150
- return res.json({
151
- statusCode: 502,
152
- message: "DBName / DBAddress is not provided.",
153
- data: {}
154
- });
155
- }
156
- }
157
- });
158
- }
159
- else {
160
- _this.SendErrorResponse(req, res);
161
- }
162
- };
163
- /**
164
- * @param Error
165
- * @param req
166
- * @param res
167
- * @param next
168
- * @description middleware: To handle Unexpected Error
169
- */
170
- this.ErrorHandler = function (Error, req, res, next) { return __awaiter(_this, void 0, void 0, function () {
171
- var errorConfig, _a, mailObj, errorObj, db, saveObj, error_1;
172
- return __generator(this, function (_b) {
173
- switch (_b.label) {
174
- case 0:
175
- if (Error && Error.SendResponse != false) {
176
- this.ReturnJsonResponse(req, res, {
177
- OriginalStatus: 500,
178
- Status: 500,
179
- Message: "Something went wrong",
180
- Data: {},
181
- Type: "ERROR"
182
- });
183
- }
184
- errorConfig = { ErrorReportFrom: this.masterConfig.ERROR_REPORT_FROM, ErrorReportTo: this.masterConfig.ERROR_REPORT_TO };
185
- _a = errorHandler_1.default(Error, req, errorConfig), mailObj = _a.mailObj, errorObj = _a.errorObj;
186
- _b.label = 1;
187
- case 1:
188
- _b.trys.push([1, 5, , 6]);
189
- return [4 /*yield*/, this.ConnectToCompanyDB(req.DBName || this.masterConfig.MASTER_DB_NAME)];
190
- case 2:
191
- db = _b.sent();
192
- mail_1.SendMail(mailObj, {
193
- SES_ACCESS_ID: this.masterConfig.SES_ACCESS_ID,
194
- SES_SECRET_KEY: this.masterConfig.SES_SECRET_KEY,
195
- SES_REGION: this.masterConfig.SES_REGION
196
- }).then(function (response) {
197
- // console.log(response)
198
- }).catch(function (err) {
199
- console.log("Error While SendMail. => ", err);
200
- });
201
- if (!db) return [3 /*break*/, 4];
202
- return [4 /*yield*/, db.collection("Error").insertOne(errorObj)];
203
- case 3:
204
- saveObj = _b.sent();
205
- _b.label = 4;
206
- case 4: return [3 /*break*/, 6];
207
- case 5:
208
- error_1 = _b.sent();
209
- console.log("Error While connectin to Master DB", error_1);
210
- return [3 /*break*/, 6];
211
- case 6: return [2 /*return*/];
212
- }
213
- });
214
- }); };
215
- /**
216
- * @param LogsDasbaseType
217
- * @param LogsDatabaseHost
218
- * @param LogsDabaseName
219
- * @param LogsDatabaseUserName
220
- * @param LogsDatabasePassword
221
- * @param LogsDatabasePort
222
- * @description Helper function to send response
223
- */
224
- this.ConnectToLogsDB = function (LogsDasbaseType, LogsDatabaseHost, LogsDabaseName, LogsDatabaseUserName, LogsDatabasePassword, LogsDatabasePort) { return __awaiter(_this, void 0, void 0, function () {
225
- var sequelize;
226
- return __generator(this, function (_a) {
227
- switch (_a.label) {
228
- case 0:
229
- if (!!this.connections['SQLConn']) return [3 /*break*/, 2];
230
- sequelize = new sequelize_1.Sequelize(LogsDabaseName, LogsDatabaseUserName, LogsDatabasePassword, {
231
- logging: false,
232
- host: LogsDatabaseHost,
233
- port: LogsDatabasePort,
234
- dialect: LogsDasbaseType,
235
- pool: {
236
- max: 10,
237
- min: 1,
238
- acquire: 30000,
239
- idle: 10000
240
- }
241
- });
242
- return [4 /*yield*/, sequelize.authenticate().catch(function (err) {
243
- console.log('Error Connecting to logs Database:', err);
244
- throw err;
245
- })];
246
- case 1:
247
- _a.sent();
248
- sequelize.sync();
249
- this.connections['SQLConn'] = sequelize;
250
- console.log('Connected to logs database ...');
251
- return [2 /*return*/, sequelize];
252
- case 2:
253
- this.connections['SQLConn'].sync();
254
- return [2 /*return*/, this.connections['SQLConn']];
255
- }
256
- });
257
- }); };
258
- /**
259
- * @param req
260
- * @param res
261
- * @param params
262
- * @description Helper function to send response
263
- */
264
- this.ReturnJsonResponse = function (req, res, params) {
265
- if (!params.Status || !params.Message) {
266
- throw new Error("Invalid Response Structure");
267
- }
268
- res.status(params.OriginalStatus || 200).json({
269
- statusCode: params.Status,
270
- message: params.Message,
271
- data: params.Data
272
- });
273
- };
274
- this.ConnectToDb({
275
- DBAddress: masterConfig.MASTER_CONNECTION_STRING,
276
- DBName: masterConfig.MASTER_DB_NAME
277
- });
278
- //to setup global mail Config
279
- new mail_1.MailSetup(masterConfig);
280
- }
281
- /**
282
- * @param tokenData contains connection details of database
283
- * @param next
284
- * @return Promise
285
- * @description make connection to database when url and dbname is passed
286
- */
287
- Connection.prototype.ConnectToDb = function (tokenData, next) {
288
- var _this = this;
289
- return new Promise(function (resolve, reject) {
290
- var connectionString = tokenData.DBAddress;
291
- //If connection exist then resolve
292
- if (_this.connections && _this.connections[Buffer.from(connectionString).toString('base64')]) {
293
- // console.log("resue")
294
- return resolve();
295
- }
296
- //If connection missing create and set it to connections object
297
- mongodb_1.MongoClient.connect(connectionString, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
298
- if (err) {
299
- resolve();
300
- if (next) {
301
- next(err);
302
- }
303
- }
304
- // let connection = client.db(tokenData.DBName);
305
- _this.connections[Buffer.from(connectionString).toString('base64')] = client;
306
- resolve();
307
- });
308
- });
309
- };
310
- /**
311
- *
312
- * @param resolve
313
- * @param reject
314
- * @param DBName
315
- * @description helper middleware function: find connection details from Master DB and create connection
316
- */
317
- Connection.prototype.GetCompanyConnection = function (resolve, reject, DBName) {
318
- this.ConnectToCompanyDB(DBName).then(function (connection) { return resolve(connection); }).catch(function (e) { return reject(e); });
319
- };
320
- /**
321
- *
322
- * @param DBName
323
- * @description helper function
324
- */
325
- Connection.prototype.FindAndReturnDBConnection = function (DBName, DBAddress) {
326
- var _this = this;
327
- /*Code Updated By Suraj on 07-Apr-2022, Try catch and some If conditions added to prevent from breaking the code.*/
328
- return new Promise(function (resolve, reject) {
329
- try {
330
- if (DBAddress && _this.connections[Buffer.from(DBAddress).toString('base64')]) {
331
- _this.connections[Buffer.from(DBAddress).toString('base64')].db(DBName);
332
- }
333
- var masterDb = null;
334
- if (_this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]) {
335
- masterDb = _this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].db(_this.masterConfig.MASTER_DB_NAME);
336
- }
337
- //checking master db connection
338
- if (!masterDb) {
339
- console.log("Master db connection not available");
340
- reject(new Error("Master db connection not available"));
341
- return;
342
- }
343
- if (DBName == _this.masterConfig.MASTER_DB_NAME) {
344
- return resolve(masterDb);
345
- }
346
- masterDb.collection("Company").findOne({ DBName: DBName }).then(function (companyData) {
347
- if (companyData) {
348
- _this.ConnectToDb({
349
- DBAddress: companyData.DBAddress,
350
- DBName: companyData.DBName
351
- }).then(function () {
352
- //Checking company connection first, if exists then resolve
353
- if (_this.connections[Buffer.from(companyData.DBAddress).toString('base64')]) {
354
- resolve(_this.connections[Buffer.from(companyData.DBAddress).toString('base64')].db(companyData.DBName));
355
- }
356
- else {
357
- console.log("Company db connection not established");
358
- reject(new Error("Company db connection not established"));
359
- }
360
- });
361
- }
362
- else {
363
- reject();
364
- }
365
- }, function (error) {
366
- console.log("Error occurred :", error);
367
- reject(error);
368
- });
369
- }
370
- catch (ex) {
371
- console.log("Error occurred :", ex);
372
- ex.message += "- db connection error";
373
- reject(ex);
374
- }
375
- });
376
- };
377
- /**
378
- * @param DBName
379
- * @returns Promise
380
- * @description return connection when dbName is passed, if connection is available it will create the connection
381
- */
382
- Connection.prototype.ConnectToCompanyDB = function (DBName, DBAddress) {
383
- return __awaiter(this, void 0, void 0, function () {
384
- return __generator(this, function (_a) {
385
- switch (_a.label) {
386
- case 0:
387
- if (!(this.connections && this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')])) return [3 /*break*/, 1];
388
- return [2 /*return*/, this.FindAndReturnDBConnection(DBName, DBAddress)];
389
- case 1: return [4 /*yield*/, this.ConnectToDb({
390
- DBAddress: this.masterConfig.MASTER_CONNECTION_STRING,
391
- DBName: this.masterConfig.MASTER_DB_NAME
392
- })];
393
- case 2:
394
- _a.sent();
395
- return [2 /*return*/, this.FindAndReturnDBConnection(DBName, DBAddress)];
396
- }
397
- });
398
- });
399
- };
400
- /**
401
- *
402
- * @param req
403
- * @param res
404
- * @description helper function: To send error if validation failed
405
- */
406
- Connection.prototype.SendErrorResponse = function (req, res) {
407
- return __awaiter(this, void 0, void 0, function () {
408
- var db;
409
- var _this = this;
410
- return __generator(this, function (_a) {
411
- switch (_a.label) {
412
- case 0:
413
- if (!req.cookies.msp_d) {
414
- return [2 /*return*/, this.ReturnJsonResponse(req, res, {
415
- Data: {},
416
- Message: "No token provided.",
417
- Status: 403,
418
- OriginalStatus: 403,
419
- Type: "ERROR"
420
- })];
421
- }
422
- return [4 /*yield*/, this.ConnectToCompanyDB(this.masterConfig.MASTER_DB_NAME, this.masterConfig.MASTER_CONNECTION_STRING)];
423
- case 1:
424
- db = _a.sent();
425
- if (!(db instanceof mongodb_1.Db)) {
426
- return [2 /*return*/, this.ReturnJsonResponse(req, res, {
427
- Data: {},
428
- Message: "Connection not stablished.",
429
- Status: 500,
430
- OriginalStatus: 500,
431
- Type: "ERROR"
432
- })];
433
- }
434
- db.collection("User").findOne({ _id: new mongodb_1.ObjectId(req.cookies.msp_d.ui) }).then(function (user) {
435
- if (!user) {
436
- return _this.ReturnJsonResponse(req, res, {
437
- Data: {},
438
- Message: "Your previous session has expired. Please log in.",
439
- Status: 401,
440
- Type: "ERROR",
441
- OriginalStatus: 401
442
- });
443
- }
444
- else {
445
- if (user.UserStatus == "Active") {
446
- return _this.ReturnJsonResponse(req, res, {
447
- Data: {},
448
- Message: "No token provided.",
449
- Status: 403,
450
- Type: "ERROR",
451
- OriginalStatus: 403
452
- });
453
- }
454
- else {
455
- return _this.ReturnJsonResponse(req, res, {
456
- Data: {},
457
- Message: "Failed to authenticate token.",
458
- Status: 401,
459
- Type: "ERROR",
460
- OriginalStatus: 401
461
- });
462
- }
463
- }
464
- });
465
- return [2 /*return*/];
466
- }
467
- });
468
- });
469
- };
470
- /**
471
- *
472
- * @param DBName optional parameter : if not present then connection will be stablished from the db in request
473
- * @description Sync method to get the connection from the already created connections
474
- * @returns connection || undefined
475
- */
476
- Connection.prototype.GetConnection = function (req, DBName, DBAddress) {
477
- var dbname = DBName ? DBName : req.DBName;
478
- var dbaddress = DBAddress ? DBAddress : req.DBAddress;
479
- if (dbaddress && this.connections[Buffer.from(dbaddress).toString('base64')]) {
480
- return this.connections[Buffer.from(dbaddress).toString('base64')].db(dbname);
481
- }
482
- else {
483
- if (!dbaddress) {
484
- return new Error("DBAdress required");
485
- }
486
- else {
487
- return new Error("Connection not stablished");
488
- }
489
- }
490
- };
491
- /**
492
- * @description Get the name of companies which connection are available
493
- */
494
- Connection.prototype.GetActiveDBConnections = function () {
495
- return Object.keys(this.connections);
496
- };
497
- /**
498
- * @param DBName
499
- * @returns Promise
500
- * @description return session from client
501
- */
502
- Connection.prototype.GetDBSession = function (dbName, dbAddress) {
503
- return __awaiter(this, void 0, void 0, function () {
504
- var _this = this;
505
- return __generator(this, function (_a) {
506
- return [2 /*return*/, new Promise(function (resolve, reject) {
507
- try {
508
- // if (this.connections && this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]) {
509
- //return this.FindAndReturnDBConnection(DBName, DBAddress)
510
- // if (dbName == this.masterConfig.MASTER_DB_NAME) {
511
- // resolve([undefined, this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].startSession()]);
512
- // }
513
- if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
514
- resolve([undefined, _this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].startSession()]);
515
- }
516
- else {
517
- _this.ConnectToDb({
518
- DBAddress: dbAddress,
519
- DBName: dbName
520
- }).then(function (success) {
521
- if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
522
- resolve([undefined, _this.connections[Buffer.from(dbAddress).toString('base64')].startSession()]);
523
- }
524
- else {
525
- resolve([undefined, undefined]);
526
- }
527
- });
528
- }
529
- // } else {
530
- // let masterdb = await this.ConnectToDb({
531
- // DBAddress: this.masterConfig.MASTER_CONNECTION_STRING,
532
- // DBName: this.masterConfig.MASTER_DB_NAME
533
- // })
534
- // return this.FindAndReturnDBConnection(DBName, DBAddress)
535
- // }
536
- }
537
- catch (ex) {
538
- //To Do: Error pass properly
539
- resolve([new Error('Error in Get db session'), undefined]);
540
- }
541
- })];
542
- });
543
- });
544
- };
545
- /**
546
- * @param DBName
547
- * @returns Promise
548
- * @description return session from client
549
- */
550
- Connection.prototype.GetDBClient = function (dbName, dbAddress) {
551
- return __awaiter(this, void 0, void 0, function () {
552
- var _this = this;
553
- return __generator(this, function (_a) {
554
- return [2 /*return*/, new Promise(function (resolve, reject) {
555
- try {
556
- // if (this.connections && this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]) {
557
- //return this.FindAndReturnDBConnection(DBName, DBAddress)
558
- // if (dbName == this.masterConfig.MASTER_DB_NAME) {
559
- // resolve([undefined, this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].startSession()]);
560
- // }
561
- if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
562
- resolve([undefined, _this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]]);
563
- }
564
- else {
565
- _this.ConnectToDb({
566
- DBAddress: dbAddress,
567
- DBName: dbName
568
- }).then(function (success) {
569
- if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
570
- resolve([undefined, _this.connections[Buffer.from(dbAddress).toString('base64')]]);
571
- }
572
- else {
573
- resolve([undefined, undefined]);
574
- }
575
- });
576
- }
577
- // } else {
578
- // let masterdb = await this.ConnectToDb({
579
- // DBAddress: this.masterConfig.MASTER_CONNECTION_STRING,
580
- // DBName: this.masterConfig.MASTER_DB_NAME
581
- // })
582
- // return this.FindAndReturnDBConnection(DBName, DBAddress)
583
- // }
584
- }
585
- catch (ex) {
586
- //To Do: Error pass properly
587
- resolve([new Error('Error in Get db session'), undefined]);
588
- }
589
- })];
590
- });
591
- });
592
- };
593
- return Connection;
594
- }());
595
- exports.Connection = Connection;
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.Connection = void 0;
43
+ var mongodb_1 = require("mongodb");
44
+ var sequelize_1 = require("sequelize");
45
+ var errorHandler_1 = __importDefault(require("../utility/errorHandler"));
46
+ var mail_1 = require("../utility/mail");
47
+ var Connection = /** @class */ (function () {
48
+ /**
49
+ * @param masterConfig Master Connectivity Object
50
+ * @param redisClient Redisclient
51
+ * @description connect to master database and maintain master config and redis client for furture ref
52
+ */
53
+ function Connection(masterConfig, redisClient) {
54
+ var _this = this;
55
+ this.masterConfig = masterConfig;
56
+ this.redisClient = redisClient;
57
+ this.connections = {};
58
+ /**
59
+ *
60
+ * @param req
61
+ * @param res
62
+ * @param next
63
+ * @description middleware function : create database connection if not present
64
+ */
65
+ this.DbConnection = function (req, res, next) {
66
+ if (!req.DBName || !req.DBAddress) {
67
+ next("Dbname or DbAddress not defined");
68
+ }
69
+ else if (!_this.connections[Buffer.from(req.DBAddress).toString('base64')]) {
70
+ _this.ConnectToDb({
71
+ DBName: req.DBName,
72
+ DBAddress: req.DBAddress
73
+ }, next).then(function () {
74
+ next();
75
+ });
76
+ }
77
+ else {
78
+ next();
79
+ }
80
+ };
81
+ /**
82
+ *
83
+ * @param req
84
+ * @param res
85
+ * @param next
86
+ * @description middleware function : to validate the cookies that are passed in request
87
+ */
88
+ this.ValidateSession = function (req, res, next) {
89
+ // If the header 'x-access-token' exists, override the req.cookies.msp_d.token
90
+ if (req.headers['x-access-token']) {
91
+ if (!req.cookies)
92
+ req.cookies = {};
93
+ if (!req.cookies.msp_d)
94
+ req.cookies.msp_d = {};
95
+ req.cookies.msp_d.token = req.headers['x-access-token'];
96
+ }
97
+ if (req.cookies && req.cookies.msp_d && _this.redisClient) {
98
+ _this.redisClient.hgetall(req.cookies.msp_d.token, function (err, tokenData) {
99
+ if (tokenData === undefined || tokenData === null || Object.keys(tokenData).length == 0) {
100
+ req.cookies.msp_d = tokenData; /* Now no need to keep ui/upi/ci on client side. */
101
+ var masterObj = {
102
+ DBName: _this.masterConfig.MASTER_DB_NAME,
103
+ DBAddress: _this.masterConfig.MASTER_CONNECTION_STRING,
104
+ };
105
+ if (_this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]) {
106
+ _this.SendErrorResponse(req, res);
107
+ }
108
+ else {
109
+ _this.ConnectToDb(masterObj, next).then(function () {
110
+ _this.SendErrorResponse(req, res);
111
+ });
112
+ }
113
+ }
114
+ else {
115
+ req.cookies.msp_d = tokenData; /* Now no need to keep ui/upi/ci on client side. */
116
+ req["DBName"] = tokenData.DBName;
117
+ req["StorageType"] = tokenData.StorageType;
118
+ req["DBAddress"] = tokenData.DBAddress;
119
+ req["StorageSettings"] = JSON.parse(tokenData.StorageSettings);
120
+ if ((parseInt(tokenData.TimeOut) > 0) && _this.redisClient) {
121
+ _this.redisClient.expire((req.cookies.msp_d.token).toString(), parseInt(tokenData.TimeOut));
122
+ }
123
+ next();
124
+ }
125
+ });
126
+ }
127
+ else if (req.headers['is-system'] && req.headers['system-token'] && req.headers['system-type'] && _this.redisClient) {
128
+ /** TODO::
129
+ * Validate Session from Redis
130
+ * Update system type in redisClient
131
+ */
132
+ _this.redisClient.hgetall((req.headers['system-token']).toString(), function (err, systemTokenData) {
133
+ if (systemTokenData === undefined || systemTokenData === null || Object.keys(systemTokenData).length == 0) {
134
+ /* Token not Validated. */
135
+ return res.json({
136
+ statusCode: 401,
137
+ message: "Not Authorized.",
138
+ data: {}
139
+ });
140
+ }
141
+ else {
142
+ /* Validated. */
143
+ if (req.headers['db-name'] && req.headers['db-address']) {
144
+ req["DBName"] = (req.headers['db-name']).toString();
145
+ req["DBAddress"] = (req.headers['db-address']).toString();
146
+ next();
147
+ }
148
+ else {
149
+ /* DBName / DBAddress is not provided. */
150
+ return res.json({
151
+ statusCode: 502,
152
+ message: "DBName / DBAddress is not provided.",
153
+ data: {}
154
+ });
155
+ }
156
+ }
157
+ });
158
+ }
159
+ else {
160
+ _this.SendErrorResponse(req, res);
161
+ }
162
+ };
163
+ /**
164
+ * @param Error
165
+ * @param req
166
+ * @param res
167
+ * @param next
168
+ * @description middleware: To handle Unexpected Error
169
+ */
170
+ this.ErrorHandler = function (Error, req, res, next) { return __awaiter(_this, void 0, void 0, function () {
171
+ var errorConfig, _a, mailObj, errorObj, db, saveObj, error_1;
172
+ return __generator(this, function (_b) {
173
+ switch (_b.label) {
174
+ case 0:
175
+ if (Error && Error.SendResponse != false) {
176
+ this.ReturnJsonResponse(req, res, {
177
+ OriginalStatus: 500,
178
+ Status: 500,
179
+ Message: "Something went wrong",
180
+ Data: {},
181
+ Type: "ERROR"
182
+ });
183
+ }
184
+ errorConfig = { ErrorReportFrom: this.masterConfig.ERROR_REPORT_FROM, ErrorReportTo: this.masterConfig.ERROR_REPORT_TO };
185
+ _a = (0, errorHandler_1.default)(Error, req, errorConfig), mailObj = _a.mailObj, errorObj = _a.errorObj;
186
+ _b.label = 1;
187
+ case 1:
188
+ _b.trys.push([1, 5, , 6]);
189
+ return [4 /*yield*/, this.ConnectToCompanyDB(req.DBName || this.masterConfig.MASTER_DB_NAME)];
190
+ case 2:
191
+ db = _b.sent();
192
+ (0, mail_1.SendMail)(mailObj, {
193
+ SES_ACCESS_ID: this.masterConfig.SES_ACCESS_ID,
194
+ SES_SECRET_KEY: this.masterConfig.SES_SECRET_KEY,
195
+ SES_REGION: this.masterConfig.SES_REGION
196
+ }).then(function (response) {
197
+ // console.log(response)
198
+ }).catch(function (err) {
199
+ console.log("Error While SendMail. => ", err);
200
+ });
201
+ if (!db) return [3 /*break*/, 4];
202
+ return [4 /*yield*/, db.collection("Error").insertOne(errorObj)];
203
+ case 3:
204
+ saveObj = _b.sent();
205
+ _b.label = 4;
206
+ case 4: return [3 /*break*/, 6];
207
+ case 5:
208
+ error_1 = _b.sent();
209
+ console.log("Error While connectin to Master DB", error_1);
210
+ return [3 /*break*/, 6];
211
+ case 6: return [2 /*return*/];
212
+ }
213
+ });
214
+ }); };
215
+ /**
216
+ * @param LogsDasbaseType
217
+ * @param LogsDatabaseHost
218
+ * @param LogsDabaseName
219
+ * @param LogsDatabaseUserName
220
+ * @param LogsDatabasePassword
221
+ * @param LogsDatabasePort
222
+ * @description Helper function to send response
223
+ */
224
+ this.ConnectToLogsDB = function (LogsDasbaseType, LogsDatabaseHost, LogsDabaseName, LogsDatabaseUserName, LogsDatabasePassword, LogsDatabasePort) { return __awaiter(_this, void 0, void 0, function () {
225
+ var sequelize;
226
+ return __generator(this, function (_a) {
227
+ switch (_a.label) {
228
+ case 0:
229
+ if (!!this.connections['SQLConn']) return [3 /*break*/, 2];
230
+ sequelize = new sequelize_1.Sequelize(LogsDabaseName, LogsDatabaseUserName, LogsDatabasePassword, {
231
+ logging: false,
232
+ host: LogsDatabaseHost,
233
+ port: LogsDatabasePort,
234
+ dialect: LogsDasbaseType,
235
+ pool: {
236
+ max: 10,
237
+ min: 1,
238
+ acquire: 30000,
239
+ idle: 10000
240
+ }
241
+ });
242
+ return [4 /*yield*/, sequelize.authenticate().catch(function (err) {
243
+ console.log('Error Connecting to logs Database:', err);
244
+ throw err;
245
+ })];
246
+ case 1:
247
+ _a.sent();
248
+ sequelize.sync();
249
+ this.connections['SQLConn'] = sequelize;
250
+ console.log('Connected to logs database ...');
251
+ return [2 /*return*/, sequelize];
252
+ case 2:
253
+ this.connections['SQLConn'].sync();
254
+ return [2 /*return*/, this.connections['SQLConn']];
255
+ }
256
+ });
257
+ }); };
258
+ /**
259
+ * @param req
260
+ * @param res
261
+ * @param params
262
+ * @description Helper function to send response
263
+ */
264
+ this.ReturnJsonResponse = function (req, res, params) {
265
+ if (!params.Status || !params.Message) {
266
+ throw new Error("Invalid Response Structure");
267
+ }
268
+ res.status(params.OriginalStatus || 200).json({
269
+ statusCode: params.Status,
270
+ message: params.Message,
271
+ data: params.Data
272
+ });
273
+ };
274
+ this.ConnectToDb({
275
+ DBAddress: masterConfig.MASTER_CONNECTION_STRING,
276
+ DBName: masterConfig.MASTER_DB_NAME
277
+ });
278
+ //to setup global mail Config
279
+ new mail_1.MailSetup(masterConfig);
280
+ }
281
+ /**
282
+ * @param tokenData contains connection details of database
283
+ * @param next
284
+ * @return Promise
285
+ * @description make connection to database when url and dbname is passed
286
+ */
287
+ Connection.prototype.ConnectToDb = function (tokenData, next) {
288
+ var _this = this;
289
+ return new Promise(function (resolve, reject) {
290
+ var connectionString = tokenData.DBAddress;
291
+ //If connection exist then resolve
292
+ if (_this.connections && _this.connections[Buffer.from(connectionString).toString('base64')]) {
293
+ // console.log("resue")
294
+ return resolve();
295
+ }
296
+ //If connection missing create and set it to connections object
297
+ mongodb_1.MongoClient.connect(connectionString, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, client) {
298
+ if (err) {
299
+ resolve();
300
+ if (next) {
301
+ next(err);
302
+ }
303
+ }
304
+ // let connection = client.db(tokenData.DBName);
305
+ _this.connections[Buffer.from(connectionString).toString('base64')] = client;
306
+ resolve();
307
+ });
308
+ });
309
+ };
310
+ /**
311
+ *
312
+ * @param resolve
313
+ * @param reject
314
+ * @param DBName
315
+ * @description helper middleware function: find connection details from Master DB and create connection
316
+ */
317
+ Connection.prototype.GetCompanyConnection = function (resolve, reject, DBName) {
318
+ this.ConnectToCompanyDB(DBName).then(function (connection) { return resolve(connection); }).catch(function (e) { return reject(e); });
319
+ };
320
+ /**
321
+ *
322
+ * @param DBName
323
+ * @description helper function
324
+ */
325
+ Connection.prototype.FindAndReturnDBConnection = function (DBName, DBAddress) {
326
+ var _this = this;
327
+ /*Code Updated By Suraj on 07-Apr-2022, Try catch and some If conditions added to prevent from breaking the code.*/
328
+ return new Promise(function (resolve, reject) {
329
+ try {
330
+ if (DBAddress && _this.connections[Buffer.from(DBAddress).toString('base64')]) {
331
+ _this.connections[Buffer.from(DBAddress).toString('base64')].db(DBName);
332
+ }
333
+ var masterDb = null;
334
+ if (_this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]) {
335
+ masterDb = _this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].db(_this.masterConfig.MASTER_DB_NAME);
336
+ }
337
+ //checking master db connection
338
+ if (!masterDb) {
339
+ console.log("Master db connection not available");
340
+ reject(new Error("Master db connection not available"));
341
+ return;
342
+ }
343
+ if (DBName == _this.masterConfig.MASTER_DB_NAME) {
344
+ return resolve(masterDb);
345
+ }
346
+ masterDb.collection("Company").findOne({ DBName: DBName }).then(function (companyData) {
347
+ if (companyData) {
348
+ _this.ConnectToDb({
349
+ DBAddress: companyData.DBAddress,
350
+ DBName: companyData.DBName
351
+ }).then(function () {
352
+ //Checking company connection first, if exists then resolve
353
+ if (_this.connections[Buffer.from(companyData.DBAddress).toString('base64')]) {
354
+ resolve(_this.connections[Buffer.from(companyData.DBAddress).toString('base64')].db(companyData.DBName));
355
+ }
356
+ else {
357
+ console.log("Company db connection not established");
358
+ reject(new Error("Company db connection not established"));
359
+ }
360
+ });
361
+ }
362
+ else {
363
+ reject();
364
+ }
365
+ }, function (error) {
366
+ console.log("Error occurred :", error);
367
+ reject(error);
368
+ });
369
+ }
370
+ catch (ex) {
371
+ console.log("Error occurred :", ex);
372
+ ex.message += "- db connection error";
373
+ reject(ex);
374
+ }
375
+ });
376
+ };
377
+ /**
378
+ * @param DBName
379
+ * @returns Promise
380
+ * @description return connection when dbName is passed, if connection is available it will create the connection
381
+ */
382
+ Connection.prototype.ConnectToCompanyDB = function (DBName, DBAddress) {
383
+ return __awaiter(this, void 0, void 0, function () {
384
+ return __generator(this, function (_a) {
385
+ switch (_a.label) {
386
+ case 0:
387
+ if (!(this.connections && this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')])) return [3 /*break*/, 1];
388
+ return [2 /*return*/, this.FindAndReturnDBConnection(DBName, DBAddress)];
389
+ case 1: return [4 /*yield*/, this.ConnectToDb({
390
+ DBAddress: this.masterConfig.MASTER_CONNECTION_STRING,
391
+ DBName: this.masterConfig.MASTER_DB_NAME
392
+ })];
393
+ case 2:
394
+ _a.sent();
395
+ return [2 /*return*/, this.FindAndReturnDBConnection(DBName, DBAddress)];
396
+ }
397
+ });
398
+ });
399
+ };
400
+ /**
401
+ *
402
+ * @param req
403
+ * @param res
404
+ * @description helper function: To send error if validation failed
405
+ */
406
+ Connection.prototype.SendErrorResponse = function (req, res) {
407
+ return __awaiter(this, void 0, void 0, function () {
408
+ var db;
409
+ var _this = this;
410
+ return __generator(this, function (_a) {
411
+ switch (_a.label) {
412
+ case 0:
413
+ if (!req.cookies.msp_d) {
414
+ return [2 /*return*/, this.ReturnJsonResponse(req, res, {
415
+ Data: {},
416
+ Message: "No token provided.",
417
+ Status: 403,
418
+ OriginalStatus: 403,
419
+ Type: "ERROR"
420
+ })];
421
+ }
422
+ return [4 /*yield*/, this.ConnectToCompanyDB(this.masterConfig.MASTER_DB_NAME, this.masterConfig.MASTER_CONNECTION_STRING)];
423
+ case 1:
424
+ db = _a.sent();
425
+ if (!(db instanceof mongodb_1.Db)) {
426
+ return [2 /*return*/, this.ReturnJsonResponse(req, res, {
427
+ Data: {},
428
+ Message: "Connection not stablished.",
429
+ Status: 500,
430
+ OriginalStatus: 500,
431
+ Type: "ERROR"
432
+ })];
433
+ }
434
+ db.collection("User").findOne({ _id: new mongodb_1.ObjectId(req.cookies.msp_d.ui) }).then(function (user) {
435
+ if (!user) {
436
+ return _this.ReturnJsonResponse(req, res, {
437
+ Data: {},
438
+ Message: "Your previous session has expired. Please log in.",
439
+ Status: 401,
440
+ Type: "ERROR",
441
+ OriginalStatus: 401
442
+ });
443
+ }
444
+ else {
445
+ if (user.UserStatus == "Active") {
446
+ return _this.ReturnJsonResponse(req, res, {
447
+ Data: {},
448
+ Message: "No token provided.",
449
+ Status: 403,
450
+ Type: "ERROR",
451
+ OriginalStatus: 403
452
+ });
453
+ }
454
+ else {
455
+ return _this.ReturnJsonResponse(req, res, {
456
+ Data: {},
457
+ Message: "Failed to authenticate token.",
458
+ Status: 401,
459
+ Type: "ERROR",
460
+ OriginalStatus: 401
461
+ });
462
+ }
463
+ }
464
+ });
465
+ return [2 /*return*/];
466
+ }
467
+ });
468
+ });
469
+ };
470
+ /**
471
+ *
472
+ * @param DBName optional parameter : if not present then connection will be stablished from the db in request
473
+ * @description Sync method to get the connection from the already created connections
474
+ * @returns connection || undefined
475
+ */
476
+ Connection.prototype.GetConnection = function (req, DBName, DBAddress) {
477
+ var dbname = DBName ? DBName : req.DBName;
478
+ var dbaddress = DBAddress ? DBAddress : req.DBAddress;
479
+ if (dbaddress && this.connections[Buffer.from(dbaddress).toString('base64')]) {
480
+ return this.connections[Buffer.from(dbaddress).toString('base64')].db(dbname);
481
+ }
482
+ else {
483
+ if (!dbaddress) {
484
+ return new Error("DBAdress required");
485
+ }
486
+ else {
487
+ return new Error("Connection not stablished");
488
+ }
489
+ }
490
+ };
491
+ /**
492
+ * @description Get the name of companies which connection are available
493
+ */
494
+ Connection.prototype.GetActiveDBConnections = function () {
495
+ return Object.keys(this.connections);
496
+ };
497
+ /**
498
+ * @param DBName
499
+ * @returns Promise
500
+ * @description return session from client
501
+ */
502
+ Connection.prototype.GetDBSession = function (dbName, dbAddress) {
503
+ return __awaiter(this, void 0, void 0, function () {
504
+ var _this = this;
505
+ return __generator(this, function (_a) {
506
+ return [2 /*return*/, new Promise(function (resolve, reject) {
507
+ try {
508
+ // if (this.connections && this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]) {
509
+ //return this.FindAndReturnDBConnection(DBName, DBAddress)
510
+ // if (dbName == this.masterConfig.MASTER_DB_NAME) {
511
+ // resolve([undefined, this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].startSession()]);
512
+ // }
513
+ if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
514
+ resolve([undefined, _this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].startSession()]);
515
+ }
516
+ else {
517
+ _this.ConnectToDb({
518
+ DBAddress: dbAddress,
519
+ DBName: dbName
520
+ }).then(function (success) {
521
+ if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
522
+ resolve([undefined, _this.connections[Buffer.from(dbAddress).toString('base64')].startSession()]);
523
+ }
524
+ else {
525
+ resolve([undefined, undefined]);
526
+ }
527
+ });
528
+ }
529
+ // } else {
530
+ // let masterdb = await this.ConnectToDb({
531
+ // DBAddress: this.masterConfig.MASTER_CONNECTION_STRING,
532
+ // DBName: this.masterConfig.MASTER_DB_NAME
533
+ // })
534
+ // return this.FindAndReturnDBConnection(DBName, DBAddress)
535
+ // }
536
+ }
537
+ catch (ex) {
538
+ //To Do: Error pass properly
539
+ resolve([new Error('Error in Get db session'), undefined]);
540
+ }
541
+ })];
542
+ });
543
+ });
544
+ };
545
+ /**
546
+ * @param DBName
547
+ * @returns Promise
548
+ * @description return session from client
549
+ */
550
+ Connection.prototype.GetDBClient = function (dbName, dbAddress) {
551
+ return __awaiter(this, void 0, void 0, function () {
552
+ var _this = this;
553
+ return __generator(this, function (_a) {
554
+ return [2 /*return*/, new Promise(function (resolve, reject) {
555
+ try {
556
+ // if (this.connections && this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]) {
557
+ //return this.FindAndReturnDBConnection(DBName, DBAddress)
558
+ // if (dbName == this.masterConfig.MASTER_DB_NAME) {
559
+ // resolve([undefined, this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].startSession()]);
560
+ // }
561
+ if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
562
+ resolve([undefined, _this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]]);
563
+ }
564
+ else {
565
+ _this.ConnectToDb({
566
+ DBAddress: dbAddress,
567
+ DBName: dbName
568
+ }).then(function (success) {
569
+ if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
570
+ resolve([undefined, _this.connections[Buffer.from(dbAddress).toString('base64')]]);
571
+ }
572
+ else {
573
+ resolve([undefined, undefined]);
574
+ }
575
+ });
576
+ }
577
+ // } else {
578
+ // let masterdb = await this.ConnectToDb({
579
+ // DBAddress: this.masterConfig.MASTER_CONNECTION_STRING,
580
+ // DBName: this.masterConfig.MASTER_DB_NAME
581
+ // })
582
+ // return this.FindAndReturnDBConnection(DBName, DBAddress)
583
+ // }
584
+ }
585
+ catch (ex) {
586
+ //To Do: Error pass properly
587
+ resolve([new Error('Error in Get db session'), undefined]);
588
+ }
589
+ })];
590
+ });
591
+ });
592
+ };
593
+ return Connection;
594
+ }());
595
+ exports.Connection = Connection;