exodus-framework 2.0.953 → 2.0.955

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 (114) hide show
  1. package/lib/app/settings.d.ts.map +1 -1
  2. package/lib/contracts/settings.d.ts +1 -2
  3. package/lib/contracts/settings.d.ts.map +1 -1
  4. package/lib/services/database.d.ts +2 -0
  5. package/lib/services/database.d.ts.map +1 -1
  6. package/lib/services/sequelize.d.ts +0 -1
  7. package/lib/services/sequelize.d.ts.map +1 -1
  8. package/lib/utils/database.d.ts +1 -2
  9. package/lib/utils/database.d.ts.map +1 -1
  10. package/package.json +1 -1
  11. package/lib/app/classes/broadcast.js +0 -79
  12. package/lib/app/classes/cache.js +0 -94
  13. package/lib/app/classes/communication.js +0 -99
  14. package/lib/app/classes/communicationcontext.js +0 -1
  15. package/lib/app/classes/event.js +0 -94
  16. package/lib/app/classes/index.js +0 -105
  17. package/lib/app/classes/managed.js +0 -145
  18. package/lib/app/classes/service.js +0 -232
  19. package/lib/app/classes/servicemodel.js +0 -22
  20. package/lib/app/classes/singleton.js +0 -26
  21. package/lib/app/classes/socket/clienthandler.js +0 -54
  22. package/lib/app/classes/socket/eventhandler.js +0 -51
  23. package/lib/app/classes/socket/index.js +0 -20
  24. package/lib/app/classes/system.js +0 -49
  25. package/lib/app/controller.js +0 -97
  26. package/lib/app/core.js +0 -47
  27. package/lib/app/error.js +0 -66
  28. package/lib/app/exodus.js +0 -97
  29. package/lib/app/index.js +0 -68
  30. package/lib/app/settings.js +0 -162
  31. package/lib/certificates/private_key.pem +0 -27
  32. package/lib/certificates/public_key.pem +0 -9
  33. package/lib/contracts/communication/communication.js +0 -39
  34. package/lib/contracts/communication/index.js +0 -27
  35. package/lib/contracts/communication/operation.js +0 -5
  36. package/lib/contracts/console.js +0 -5
  37. package/lib/contracts/contansts.js +0 -13
  38. package/lib/contracts/core.js +0 -12
  39. package/lib/contracts/entity.js +0 -5
  40. package/lib/contracts/http.js +0 -52
  41. package/lib/contracts/index.js +0 -104
  42. package/lib/contracts/messaging.js +0 -50
  43. package/lib/contracts/security.js +0 -5
  44. package/lib/contracts/service.js +0 -11
  45. package/lib/contracts/session.js +0 -5
  46. package/lib/contracts/settings.js +0 -5
  47. package/lib/contracts/singleton.js +0 -5
  48. package/lib/contracts/socket.js +0 -11
  49. package/lib/contracts/tasks.js +0 -1
  50. package/lib/controllers/api/file.js +0 -24
  51. package/lib/controllers/api/index.js +0 -13
  52. package/lib/controllers/api/log.js +0 -55
  53. package/lib/controllers/api/report.js +0 -55
  54. package/lib/controllers/index.js +0 -16
  55. package/lib/controllers/messaging/application.js +0 -75
  56. package/lib/controllers/messaging/database.js +0 -64
  57. package/lib/controllers/messaging/environment.js +0 -111
  58. package/lib/express.d.js +0 -5
  59. package/lib/index.js +0 -104
  60. package/lib/middlewares/access.js +0 -114
  61. package/lib/middlewares/authentication.js +0 -104
  62. package/lib/middlewares/file.js +0 -41
  63. package/lib/middlewares/index.js +0 -36
  64. package/lib/models/Application.js +0 -65
  65. package/lib/models/DatabaseHost.js +0 -62
  66. package/lib/models/EnvConnection.js +0 -41
  67. package/lib/models/Log.js +0 -67
  68. package/lib/models/Report.js +0 -65
  69. package/lib/models/System.js +0 -54
  70. package/lib/models/index.js +0 -82
  71. package/lib/routes/api/index.js +0 -16
  72. package/lib/routes/api/v1/index.js +0 -38
  73. package/lib/routes/api/v1/logs.js +0 -19
  74. package/lib/routes/api/v1/report.js +0 -19
  75. package/lib/routes/api/v1/sse.js +0 -36
  76. package/lib/routes/index.js +0 -27
  77. package/lib/routes/messaging/index.js +0 -34
  78. package/lib/services/database.js +0 -115
  79. package/lib/services/ecosystem.js +0 -46
  80. package/lib/services/express.js +0 -162
  81. package/lib/services/file.js +0 -65
  82. package/lib/services/file_new.js +0 -136
  83. package/lib/services/index.js +0 -108
  84. package/lib/services/log.js +0 -26
  85. package/lib/services/rabitmq.js +0 -187
  86. package/lib/services/redis.js +0 -84
  87. package/lib/services/security.js +0 -231
  88. package/lib/services/sequelize.js +0 -323
  89. package/lib/services/socket.js +0 -123
  90. package/lib/services/task/TaskServiceBase.js +0 -17
  91. package/lib/services/task/index.js +0 -40
  92. package/lib/services/task/queue/QueueService.js +0 -48
  93. package/lib/services/task/queue/QueueTask.js +0 -134
  94. package/lib/services/task/queue/SingleQueue.js +0 -68
  95. package/lib/services/task/queue/index.js +0 -27
  96. package/lib/services/task/scheduler/SchedulerService.js +0 -31
  97. package/lib/services/task/scheduler/SchedulerTask.js +0 -211
  98. package/lib/services/task/scheduler/index.js +0 -20
  99. package/lib/services/test.js +0 -27
  100. package/lib/socket.d.js +0 -3
  101. package/lib/tasks/index.js +0 -27
  102. package/lib/tasks/queue/application.js +0 -44
  103. package/lib/tasks/queue/environment.js +0 -92
  104. package/lib/tasks/queue/index.js +0 -20
  105. package/lib/tasks/queue/teste.js +0 -21
  106. package/lib/tasks/schedule/index.js +0 -13
  107. package/lib/tasks/schedule/restart.js +0 -19
  108. package/lib/tasks/schedule/teste.js +0 -61
  109. package/lib/utils/api.js +0 -65
  110. package/lib/utils/database.js +0 -155
  111. package/lib/utils/date.js +0 -28
  112. package/lib/utils/index.js +0 -60
  113. package/lib/utils/logger.js +0 -51
  114. package/lib/utils/session.js +0 -23
@@ -1,84 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _redis = require("redis");
8
- var _app = require("../app");
9
- var _service = _interopRequireDefault(require("../app/classes/service"));
10
- var _cache = require("../app/classes/cache");
11
- var _utils = require("../utils");
12
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
13
- /**
14
- * Serviço de cache
15
- *
16
- * @class RedisService
17
- * @extends {Service}
18
- * @implements {IService}
19
- */
20
- class RedisService extends _service.default {
21
- client;
22
- isReconnecting = false; // Flag para evitar múltiplas tentativas simultâneas de reconexão
23
- isConnected = false; // Flag para controlar o estado da conexão
24
-
25
- async onServiceInit() {
26
- await super.onServiceInit();
27
- this.startAttemptDelay = 5 * 1000;
28
- this.maxStartAttempts = 3;
29
- }
30
- async onStart() {
31
- await super.onStart();
32
- return this.connect();
33
- }
34
- async onStartFail() {
35
- await super.onStartFail();
36
- this.log(`Not possible to connect Redis`, 'danger');
37
- }
38
- async connect() {
39
- if (this.isConnected) return true;
40
- if (this.isReconnecting) return false;
41
- this.log(`⌛️ Connecting to Redis Server: ${this.currentStartAttempts}/${this.maxStartAttempts}`);
42
- this.isReconnecting = true;
43
- try {
44
- const queryConnect = `redis://${_app.Core.settings.getCache().host}:${_app.Core.settings.getCache().port}`;
45
- const password = _app.Core.settings.getCache().password;
46
- this.client = (0, _redis.createClient)({
47
- url: queryConnect,
48
- password
49
- });
50
- await this.client.connect();
51
- this.isConnected = true;
52
- this.isReconnecting = false;
53
- this.setupErrorHandles();
54
- this.log(`✅ Redis Connection is ready`);
55
- return true;
56
- } catch (error) {
57
- (0, _utils.logger)().error(error, `Not connected to Redis Server`);
58
- this.isReconnecting = false;
59
- return false;
60
- }
61
- }
62
- setupErrorHandles() {
63
- this.client.on('error', err => {
64
- new _app.ErrorHandler('falha na conexão Redis', err);
65
- this.isConnected = false;
66
- });
67
- }
68
-
69
- //* Common
70
- async setValue(key, value) {
71
- await this.client.set(key, value);
72
- }
73
- async getValue(key) {
74
- const value = await this.client.get(key);
75
- return value;
76
- }
77
- async deleteValue(key) {
78
- await this.client.del(key);
79
- }
80
- createCache(key) {
81
- return new _cache.RedisCache(this.client, key);
82
- }
83
- }
84
- var _default = exports.default = RedisService;
@@ -1,231 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var crypto = _interopRequireWildcard(require("crypto"));
8
- var fs = _interopRequireWildcard(require("fs"));
9
- var _nodeJose = require("node-jose");
10
- var _path = _interopRequireDefault(require("path"));
11
- var _app = require("../app");
12
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
13
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
14
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
15
- class SecurityService extends _app.Service {
16
- privateKey;
17
- publicKey;
18
- servicePublicKey;
19
- async onStart() {
20
- await super.onStart();
21
- this.checkPaths();
22
- await this.loadPrivateKey();
23
- await this.loadPublicKey();
24
- await this.loadServicePublicKey();
25
- return true;
26
- }
27
- checkPaths() {
28
- !fs.existsSync(_app.Core.settings.getAuthentication().certPath) && fs.mkdirSync(_app.Core.settings.getAuthentication().certPath, {
29
- recursive: true
30
- });
31
- }
32
-
33
- /* Key Pair */
34
- async loadPrivateKey() {
35
- const privateKeyPath = _path.default.join(_app.Core.settings.getAuthentication().certPath, 'private_key.pem');
36
- if (fs.existsSync(privateKeyPath)) {
37
- const pem = fs.readFileSync(privateKeyPath, 'utf8');
38
- this.privateKey = await _nodeJose.JWK.asKey(pem, 'pem');
39
- } else {
40
- const {
41
- privateKey
42
- } = await this.createKeyPairs();
43
- this.privateKey = await _nodeJose.JWK.asKey(privateKey, 'pem');
44
- const pem = this.privateKey.toPEM(true);
45
- fs.writeFileSync(privateKeyPath, pem, 'utf8');
46
- }
47
- }
48
- async loadPublicKey() {
49
- const publicKeyPath = _path.default.join(_app.Core.settings.getAuthentication().certPath, 'public_key.pem');
50
- const pem = this.privateKey.toPEM(false);
51
- this.publicKey = await _nodeJose.JWK.asKey(pem, 'pem');
52
- fs.writeFileSync(publicKeyPath, pem, 'utf8');
53
- }
54
- async createKeyPairs() {
55
- const keyPair = await _nodeJose.JWK.createKey('RSA', 2048, {
56
- alg: 'RS256',
57
- use: 'sig',
58
- iss: _app.Core.settings.getAuthentication().issuer
59
- });
60
- return {
61
- publicKey: keyPair.toPEM(false),
62
- privateKey: keyPair.toPEM(true)
63
- };
64
- }
65
- async loadServicePublicKey() {
66
- if (fs.existsSync(_app.Core.settings.getAuthentication().servicePublicKeyPath)) {
67
- const pem = fs.readFileSync(_app.Core.settings.getAuthentication().servicePublicKeyPath, 'utf8');
68
- this.servicePublicKey = await _nodeJose.JWK.asKey(pem, 'pem');
69
- } else {
70
- throw new Error('Não foi possível localizar o certificado de serviço. Verifique o caminho nas configurações');
71
- }
72
- }
73
- async loadKeyByStr(data) {
74
- return await _nodeJose.JWK.asKey(data, 'pem');
75
- }
76
-
77
- /**
78
- * Chave privada emitida por este serviço
79
- *
80
- * @memberof SecurityService
81
- */
82
- getPrivateKey() {
83
- return this.privateKey;
84
- }
85
- /**
86
- * Chave publica emitida por este serviço
87
- *
88
- * @memberof SecurityService
89
- */
90
- getPublicKey() {
91
- return this.publicKey;
92
- }
93
- /**
94
- * Chave publica emitida pelo serviço do hub se sessões
95
- *
96
- * @memberof SecurityService
97
- */
98
- getServicePublicKey() {
99
- return this.servicePublicKey;
100
- }
101
- /**
102
- * Criptografía utilizando chave publica
103
- *
104
- * @param {TSignData} data
105
- * @memberof SecurityService
106
- */
107
- async encrypt(data, publicKey) {
108
- const currentTime = Math.floor(Date.now() / 1000);
109
- const defaults = {
110
- iat: currentTime,
111
- exp: currentTime + _app.Core.settings.getAuthentication().signExpirationSecs,
112
- iss: _app.Core.settings.getAuthentication().issuer
113
- };
114
- const payload = JSON.stringify({
115
- ...defaults,
116
- ...data
117
- });
118
- try {
119
- const encrypted = await _nodeJose.JWE.createEncrypt({
120
- format: 'compact'
121
- }, publicKey).update(payload).final();
122
- return encrypted;
123
- } catch (error) {
124
- new _app.ErrorHandler('Não foi possível criptografar os dados', error);
125
- return false;
126
- }
127
- }
128
- /**
129
- * Descriptografia utilizando chave privada
130
- *
131
- * @param {string} encryptedData
132
- * @memberof SecurityService
133
- */
134
- async decrypt(encryptedData, privateKey) {
135
- try {
136
- const decrypted = await _nodeJose.JWE.createDecrypt(privateKey).decrypt(encryptedData);
137
- const result = decrypted.plaintext.toString();
138
- const parserd = JSON.parse(result);
139
- // Tenta parsear como JSON se for objeto
140
- return parserd.payload;
141
- } catch (error) {
142
- new _app.ErrorHandler('Não foi possível descriptografar os dados', error);
143
- return false;
144
- }
145
- }
146
- /**
147
- * Realiza uma assinatura usando chave privada
148
- *
149
- * @param {TSignData} data
150
- * @memberof SecurityService
151
- */
152
- async sign(data, privateKey) {
153
- const currentTime = Math.floor(Date.now() / 1000);
154
- const defaults = {
155
- iat: currentTime,
156
- exp: currentTime + _app.Core.settings.getAuthentication().signExpirationSecs,
157
- iss: _app.Core.settings.getAuthentication().issuer
158
- };
159
- try {
160
- const payload = JSON.stringify({
161
- ...defaults,
162
- ...data
163
- });
164
- const signature = await _nodeJose.JWS.createSign({
165
- compact: true,
166
- fields: {
167
- typ: 'jwt'
168
- }
169
- }, privateKey).update(payload, 'utf8').final();
170
- return signature;
171
- } catch (error) {
172
- new _app.ErrorHandler('Erro ao assinar os dados', error);
173
- }
174
- }
175
-
176
- /**
177
- * Verifica assinatura utilizando chave publica
178
- *
179
- * @param {string} signature
180
- * @memberof SecurityService
181
- */
182
- async verifySignature(signature, publicKey) {
183
- try {
184
- const result = await _nodeJose.JWS.createVerify(publicKey).verify(signature);
185
- const payload = result.payload.toString();
186
- return JSON.parse(payload);
187
- } catch (error) {
188
- new _app.ErrorHandler('Assinatura inválida ou erro durante a verificação', error);
189
- }
190
- }
191
-
192
- /**
193
- * Criptografía de dados utilizando um buffer automático ao invés de chaves
194
- *
195
- * @param {(string | object)} data
196
- * @memberof SecurityService
197
- */
198
- simpleEncrypt(data) {
199
- if (process.versions.openssl <= '1.0.1f') {
200
- throw new Error('OpenSSL Version too old, vulnerability to Heartbleed');
201
- }
202
- const key = crypto.randomBytes(32);
203
- const iv = crypto.randomBytes(16);
204
- const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
205
- let encrypted = cipher.update(data);
206
- encrypted = Buffer.concat([encrypted, cipher.final()]);
207
- return [iv.toString('hex') + ':' + encrypted.toString('hex'), key];
208
- }
209
- /**
210
- * Utiliza um buffer para descriptografar dados criptografados através de simpleEncrypt()
211
- *
212
- * @param {string} data
213
- * @param {Buffer} key
214
- * @memberof SecurityService
215
- */
216
- simpleDecrypt(data, key) {
217
- try {
218
- const textParts = data.split(':');
219
- const iv = Buffer.from(textParts.shift(), 'hex');
220
- const encryptedText = Buffer.from(textParts.join(':'), 'hex');
221
- const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
222
- let decrypted = decipher.update(encryptedText);
223
- decrypted = Buffer.concat([decrypted, decipher.final()]);
224
- return decrypted;
225
- } catch (error) {
226
- new _app.ErrorHandler('Erro durante a descriptografia de dados', error);
227
- return false;
228
- }
229
- }
230
- }
231
- var _default = exports.default = SecurityService;
@@ -1,323 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _sequelize = require("sequelize");
8
- var _app = require("../app");
9
- var _service = _interopRequireDefault(require("../app/classes/service"));
10
- var _models = require("../models");
11
- var _DatabaseHost = require("../models/DatabaseHost");
12
- var _database = require("../utils/database");
13
- var _logger = _interopRequireDefault(require("../utils/logger"));
14
- var _security = _interopRequireDefault(require("./security"));
15
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
16
- /**
17
- * Serviço de gerênciamento do banco de dados
18
- *
19
- * @class SequelizeService
20
- * @extends {Service}
21
- * @implements {IService}
22
- */
23
- class SequelizeService extends _service.default {
24
- serviceDB;
25
- masterDB;
26
- models;
27
- connections;
28
- initializedModels;
29
- initializingdModels;
30
- relations;
31
- isReconnecting = false; // Flag para evitar múltiplas tentativas simultâneas de reconexão
32
- isMasterConnected = false; // Flag para controlar o estado da conexão
33
- isServiceConnected = false; // Flag para controlar o estado da conexão
34
-
35
- //# Initialization
36
- async onServiceInit() {
37
- await super.onServiceInit();
38
- if (!this.models) throw new Error('Models are requireds! Call registerModels(modelsArray)');
39
- this.serviceDB = _database.serviceDB;
40
- this.masterDB = _database.masterDB;
41
- this.connections = new Map();
42
- this.initializedModels = new Map();
43
- this.initializingdModels = new Map();
44
- this.relations = new Map();
45
- this.models = [...this.models, ..._models.NativeModels];
46
- this.startAttemptDelay = 5 * 1000;
47
- this.maxStartAttempts = 3;
48
- }
49
- async onStart() {
50
- await super.onStart();
51
- if (await this.connectDatabases()) {
52
- this.log(`⌛️ Inicializando models`);
53
- await this.initModels();
54
- this.log(`✅ Models inicializados`);
55
- return true;
56
- }
57
- return false;
58
- }
59
- async onStartFail() {
60
- await super.onStartFail();
61
- this.log(`Not possible to connect database`, 'danger');
62
- }
63
- async connectDatabases() {
64
- if (this.isMasterConnected && this.isServiceConnected) return true;
65
- if (this.isReconnecting) return false;
66
- this.log(`⌛️ Connecting Sequelize to database: ${this.currentStartAttempts}/${this.maxStartAttempts}`);
67
- try {
68
- if (!this.isMasterConnected) {
69
- await this.masterDB.sync({
70
- force: false
71
- });
72
- this.isMasterConnected = true;
73
- this.log('✅ Connected master database sucessfully', 'success');
74
- }
75
- if (!this.isServiceConnected) {
76
- await this.serviceDB.sync({
77
- force: false
78
- });
79
- this.isServiceConnected = true;
80
- this.log('✅ Connected service database sucessfully', 'success');
81
- }
82
- this.log('✅ All databases connecteds sucessfully', 'success');
83
- return true;
84
- } catch (error) {
85
- (0, _logger.default)().error(error, `Not connected Sequelize to database`);
86
- this.isReconnecting = false;
87
- return false;
88
- }
89
- }
90
-
91
- // #Database
92
- async getDB(tenantId) {
93
- /* master or service */
94
- if (tenantId == _app.Core.settings.getDatabase().service.database) {
95
- return _database.serviceDB;
96
- } else if (tenantId == _app.Core.settings.getDatabase().master.database) {
97
- return _database.masterDB;
98
- }
99
- const relation = await this.getRelation(tenantId);
100
- if (!relation) return false;
101
- const key = `${relation.hostUuid}@${this.getDBName(relation.envToken)}`;
102
- return this.connections.get(key) || (await this.initDB(tenantId));
103
- }
104
- async createDB(hostUuid, name) {
105
- const host = await _DatabaseHost.DatabaseHost.findByPk(hostUuid);
106
- if (!host) {
107
- this.log('Database host information not found: ' + hostUuid);
108
- return false;
109
- }
110
- const dbQueryName = `${_app.Core.settings.getDatabase().service.database}_${name}`;
111
- const connection = await this.createConnection(hostUuid);
112
- if (connection) {
113
- try {
114
- const [results] = await connection.query(`SHOW DATABASES LIKE '${dbQueryName}';`);
115
- if (results.length === 0) {
116
- // Se o banco de dados não existir, cria-o
117
- await connection.query(`CREATE DATABASE ${dbQueryName};`);
118
- this.log(`Database "${dbQueryName}" has been created.`);
119
- return true;
120
- } else {
121
- this.log(`Database "${dbQueryName}" already exists.`);
122
- return false;
123
- }
124
- } catch (error) {
125
- new _app.ErrorHandler('Erro on creating database', error);
126
- } finally {
127
- connection.close();
128
- }
129
- }
130
- return false;
131
- }
132
- async hasDB(hostUuid, name) {
133
- const host = await _DatabaseHost.DatabaseHost.findByPk(hostUuid);
134
- if (!host) {
135
- this.log('Database host information not found: ' + hostUuid);
136
- return false;
137
- }
138
- const dbQueryName = `${_app.Core.settings.getDatabase().service.database}_${name}`;
139
- const connection = await this.createConnection(hostUuid);
140
- if (connection) {
141
- try {
142
- const [results] = await connection.query(`SHOW DATABASES LIKE '${dbQueryName}';`);
143
- return results.length > 0;
144
- } catch (error) {
145
- new _app.ErrorHandler('Erro on creating database', error);
146
- } finally {
147
- connection.close();
148
- }
149
- }
150
- return false;
151
- }
152
- async deleteDB(hostUuid, name) {
153
- const dbQueryName = `${_app.Core.settings.getDatabase().service.database}_${name}`;
154
- const connection = await this.createConnection(hostUuid);
155
- if (connection) {
156
- try {
157
- await connection.query(`DROP DATABASE IF EXISTS ${dbQueryName};`);
158
- this.log(`Database "${dbQueryName}" has been deleted.`);
159
- return true;
160
- } catch (error) {
161
- return false;
162
- } finally {
163
- connection.close();
164
- }
165
- }
166
- return false;
167
- }
168
- async initDB(tenantId) {
169
- let connection = false;
170
- if (tenantId == _app.Core.settings.getDatabase().service.database) {
171
- connection = _database.serviceDB;
172
- } else if (tenantId == _app.Core.settings.getDatabase().master.database) {
173
- connection = _database.masterDB;
174
- } else {
175
- const relation = await this.getRelation(tenantId);
176
- if (!relation) return false;
177
- const dbName = this.getDBName(relation.envToken);
178
- const key = `${relation.hostUuid}@${this.getDBName(relation.envToken)}`;
179
- if (this.connections.has(key)) return this.connections.get(key);
180
- connection = await this.createConnection(relation.hostUuid, dbName);
181
- if (connection) {
182
- this.log(`✅ Connected ${dbName} database sucessfully`, 'success');
183
- this.connections.set(key, connection);
184
- }
185
- }
186
- if (connection) {
187
- await this.initModelsByConnection(tenantId, connection);
188
- }
189
- return connection;
190
- }
191
- async initModelsByConnection(tenantId, connection) {
192
- const entities = [];
193
- await Promise.all(this.models.map(async model => {
194
- const modelKey = `${tenantId}#${model.name}`;
195
- const entity = model.initialize(connection);
196
- await entity.sync();
197
- entities.push(entity);
198
- this.initializedModels.set(modelKey, entity);
199
- }));
200
- await Promise.all(this.models.map(async model => {
201
- model.associate(entities);
202
- }));
203
- }
204
- getDBName(envToken) {
205
- return `${_app.Core.settings.getDatabase().service.database}_${envToken}`;
206
- }
207
-
208
- //#Connection
209
- reconnect(db, attempts = 2) {
210
- db.sync().then(() => {
211
- this.log('Database pronto', 'success');
212
- }).catch(reason => {
213
- this.log('Attemping to connect master database', 'warning');
214
- (0, _logger.default)().warn('Erro ao inicializar o banco de dados, tentando novamente...', reason);
215
- if (attempts > 0) {
216
- setTimeout(() => this.reconnect(db, attempts - 1), 5000);
217
- } else {
218
- new _app.ErrorHandler('Error on connecting master database', reason);
219
- }
220
- });
221
- }
222
- async createConnection(hostUuid, database) {
223
- const host = await _DatabaseHost.DatabaseHost.findByPk(hostUuid);
224
- if (!host) {
225
- this.log('createConnection:: Database host information not found: ' + hostUuid);
226
- return false;
227
- }
228
- const key = await _security.default.singleton().loadKeyByStr(host.credential);
229
- const data = await _security.default.singleton().verifySignature(host.password, key);
230
- if (!data) {
231
- this.log('createConnection::Error on decript password by credential: ' + hostUuid, 'danger');
232
- return false;
233
- }
234
- const password = data.payload;
235
- const queryHost = host.host.split(':');
236
- const sequelize = new _sequelize.Sequelize({
237
- host: queryHost[0],
238
- port: Number(queryHost[1]),
239
- dialect: host.dialect,
240
- database,
241
- username: host.username,
242
- password: password,
243
- define: {
244
- timestamps: true
245
- },
246
- timezone: '-03:00',
247
- logging: _app.Core.settings.getDatabase().service.log
248
- });
249
- return new Promise((resolve, reject) => {
250
- sequelize.authenticate().then(async () => {
251
- resolve(sequelize);
252
- }).catch(reason => {
253
- reject(reason);
254
- });
255
- });
256
- }
257
- async testConnection(data) {
258
- const sequelize = new _sequelize.Sequelize({
259
- host: data.host,
260
- port: data.port,
261
- username: data.username,
262
- password: data.password,
263
- dialect: data.dialect,
264
- timezone: '-03:00',
265
- pool: _app.Core.settings.getDatabase().service.pool,
266
- logging: _app.Core.settings.getDatabase().service.log
267
- });
268
- return new Promise(resolve => {
269
- sequelize.authenticate().then(async () => {
270
- resolve(true);
271
- }).catch(reason => {
272
- new _app.ErrorHandler('teste de conexão falhou', reason);
273
- resolve(false);
274
- }).finally(() => {
275
- sequelize.close();
276
- });
277
- });
278
- }
279
-
280
- //# Common
281
- async getRelation(tenantId) {
282
- let relation;
283
- /* fetch relation */
284
- if (this.relations.get(tenantId)) {
285
- relation = this.relations.get(tenantId);
286
- } else {
287
- relation = await _models.EnvDBHost.findOne({
288
- where: {
289
- envUuid: tenantId
290
- }
291
- });
292
- if (relation) {
293
- this.relations.set(tenantId, relation);
294
- }
295
- }
296
- return relation;
297
- }
298
-
299
- // #Entity
300
- async getModel(model, tenantId) {
301
- try {
302
- const modelKey = `${tenantId}#${model.name}`;
303
- if (!this.initializedModels.has(modelKey)) {
304
- await this.initDB(tenantId);
305
- }
306
- return this.initializedModels.get(modelKey);
307
- } catch (error) {
308
- throw new _app.ErrorHandler('Erro ao obter o model', error);
309
- }
310
- }
311
- static registerModels(models) {
312
- this.getService().models = models;
313
- }
314
- async initModels() {
315
- const tenants = await _models.EnvDBHost.findAll({
316
- attributes: ['envUuid']
317
- });
318
- for (const model of this.models) {
319
- await Promise.all(tenants.map(async t => await this.getModel(model, t.envUuid)));
320
- }
321
- }
322
- }
323
- var _default = exports.default = SequelizeService;