exodus-framework 2.0.755 → 2.0.756

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 (67) hide show
  1. package/lib/app/error.d.ts +16 -0
  2. package/lib/app/error.d.ts.map +1 -1
  3. package/lib/middlewares/access.d.ts.map +1 -1
  4. package/lib/services/express.d.ts.map +1 -1
  5. package/lib/services/rabitmq.d.ts.map +1 -1
  6. package/lib/services/redis.d.ts.map +1 -1
  7. package/lib/services/security.d.ts.map +1 -1
  8. package/lib/services/sequelize.d.ts.map +1 -1
  9. package/lib/services/socket.d.ts.map +1 -1
  10. package/lib/services/task.d.ts.map +1 -1
  11. package/lib/utils/api.d.ts.map +1 -1
  12. package/package.json +1 -1
  13. package/lib/app/app.js +0 -84
  14. package/lib/app/controller.js +0 -95
  15. package/lib/app/core.js +0 -71
  16. package/lib/app/error.js +0 -43
  17. package/lib/app/index.js +0 -72
  18. package/lib/app/service.js +0 -24
  19. package/lib/app/settings.js +0 -138
  20. package/lib/app/singleton.js +0 -29
  21. package/lib/contracts/console.js +0 -5
  22. package/lib/contracts/entity.js +0 -5
  23. package/lib/contracts/http.js +0 -50
  24. package/lib/contracts/index.js +0 -104
  25. package/lib/contracts/messaging.js +0 -25
  26. package/lib/contracts/security.js +0 -5
  27. package/lib/contracts/service.js +0 -5
  28. package/lib/contracts/session.js +0 -5
  29. package/lib/contracts/settings.js +0 -5
  30. package/lib/contracts/singleton.js +0 -5
  31. package/lib/contracts/socket.js +0 -11
  32. package/lib/controllers/api/file.js +0 -24
  33. package/lib/controllers/api/index.js +0 -13
  34. package/lib/controllers/index.js +0 -16
  35. package/lib/controllers/messaging/application.js +0 -63
  36. package/lib/controllers/messaging/database.js +0 -63
  37. package/lib/controllers/messaging/environment.js +0 -100
  38. package/lib/express.d.js +0 -5
  39. package/lib/index.js +0 -92
  40. package/lib/middlewares/access.js +0 -78
  41. package/lib/middlewares/authentication.js +0 -21
  42. package/lib/middlewares/file.js +0 -41
  43. package/lib/middlewares/index.js +0 -27
  44. package/lib/models/Application.js +0 -61
  45. package/lib/models/DatabaseHost.js +0 -62
  46. package/lib/models/EnvConnection.js +0 -41
  47. package/lib/models/index.js +0 -46
  48. package/lib/routes/index.js +0 -16
  49. package/lib/routes/messaging/index.js +0 -34
  50. package/lib/services/error.d.ts +0 -28
  51. package/lib/services/error.d.ts.map +0 -1
  52. package/lib/services/error.js +0 -52
  53. package/lib/services/express.js +0 -152
  54. package/lib/services/file.js +0 -65
  55. package/lib/services/index.js +0 -88
  56. package/lib/services/rabitmq.js +0 -102
  57. package/lib/services/redis.js +0 -60
  58. package/lib/services/security.js +0 -230
  59. package/lib/services/sequelize.js +0 -284
  60. package/lib/services/socket.js +0 -56
  61. package/lib/services/task.js +0 -165
  62. package/lib/utils/api.js +0 -50
  63. package/lib/utils/database.js +0 -157
  64. package/lib/utils/date.js +0 -28
  65. package/lib/utils/index.js +0 -60
  66. package/lib/utils/logger.js +0 -51
  67. package/lib/utils/session.js +0 -23
@@ -1,284 +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/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 _error = require("./error");
15
- var _security = _interopRequireDefault(require("./security"));
16
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
17
- /**
18
- * Serviço de gerênciamento do banco de dados
19
- *
20
- * @class SequelizeService
21
- * @extends {Service}
22
- * @implements {IService}
23
- */
24
- class SequelizeService extends _service.default {
25
- serviceDB;
26
- masterDB;
27
- models;
28
- connections;
29
- initializedModels;
30
- relations;
31
-
32
- //# Initialization
33
- constructor() {
34
- super();
35
- }
36
- async init() {
37
- this.serviceDB = _database.serviceDB;
38
- this.masterDB = _database.masterDB;
39
- this.connections = new Map();
40
- this.initializedModels = new Map();
41
- this.relations = new Map();
42
- await this.connectDatabases();
43
- }
44
- async connectDatabases() {
45
- if (!this.models) throw new _error.ApplicationException('Models are requireds! Call registerModels(modelsArray)');
46
-
47
- // #Include native models
48
- this.models = [...this.models, ..._models.NativeModels];
49
- return new Promise(resolve => {
50
- this.masterDB.sync({
51
- force: false
52
- }).then(() => {
53
- this.log('✅ Connected master database sucessfully', 'success');
54
- this.serviceDB.sync({
55
- force: false
56
- }).then(() => {
57
- this.log('✅ Connected service database sucessfully', 'success');
58
- resolve(true);
59
- }).catch(reason => {
60
- new _error.ApplicationException('Não foi possível inicializar a conexão com o ServiceDB', reason);
61
- });
62
- }).catch(reason => {
63
- new _error.ApplicationException('Não foi possível inicializar a conexão com MasterDB', reason);
64
- });
65
- });
66
- }
67
-
68
- // #Database
69
- async getDB(tenantId) {
70
- /* master or service */
71
- if (tenantId == _app.Core.settings.getDatabase().service.database) {
72
- return _database.serviceDB;
73
- } else if (tenantId == _app.Core.settings.getDatabase().master.database) {
74
- return _database.masterDB;
75
- }
76
- const relation = await this.getRelation(tenantId);
77
- if (!relation) return false;
78
- const key = `${relation.hostUuid}@${this.getDBName(relation.envToken)}`;
79
- return this.connections.get(key) || (await this.initDB(tenantId));
80
- }
81
- async createDB(hostUuid, name) {
82
- const host = await _DatabaseHost.DatabaseHost.findByPk(hostUuid);
83
- if (!host) {
84
- this.log('Database host information not found: ' + hostUuid);
85
- return false;
86
- }
87
- const dbQueryName = `${_app.Core.settings.getDatabase().service.database}_${name}`;
88
- const connection = await this.createConnection(hostUuid);
89
- if (connection) {
90
- try {
91
- const [results] = await connection.query(`SHOW DATABASES LIKE '${dbQueryName}';`);
92
- if (results.length === 0) {
93
- // Se o banco de dados não existir, cria-o
94
- await connection.query(`CREATE DATABASE ${dbQueryName};`);
95
- this.log(`Database "${dbQueryName}" has been created.`);
96
- return true;
97
- } else {
98
- this.log(`Database "${dbQueryName}" already exists.`);
99
- return false;
100
- }
101
- } catch (error) {
102
- new _error.ApplicationException('Erro on creating database', error);
103
- } finally {
104
- connection.close();
105
- }
106
- }
107
- return false;
108
- }
109
- async hasDB(hostUuid, name) {
110
- const host = await _DatabaseHost.DatabaseHost.findByPk(hostUuid);
111
- if (!host) {
112
- this.log('Database host information not found: ' + hostUuid);
113
- return false;
114
- }
115
- const dbQueryName = `${_app.Core.settings.getDatabase().service.database}_${name}`;
116
- const connection = await this.createConnection(hostUuid);
117
- if (connection) {
118
- try {
119
- const [results] = await connection.query(`SHOW DATABASES LIKE '${dbQueryName}';`);
120
- return results.length > 0;
121
- } catch (error) {
122
- new _error.ApplicationException('Erro on creating database', error);
123
- } finally {
124
- connection.close();
125
- }
126
- }
127
- return false;
128
- }
129
- async deleteDB(hostUuid, name) {
130
- const dbQueryName = `${_app.Core.settings.getDatabase().service.database}_${name}`;
131
- const connection = await this.createConnection(hostUuid);
132
- if (connection) {
133
- try {
134
- await connection.query(`DROP DATABASE IF EXISTS ${dbQueryName};`);
135
- this.log(`Database "${dbQueryName}" has been deleted.`);
136
- return true;
137
- } catch (error) {
138
- return false;
139
- } finally {
140
- connection.close();
141
- }
142
- }
143
- return false;
144
- }
145
- async initDB(tenantId) {
146
- const relation = await this.getRelation(tenantId);
147
- if (!relation) return false;
148
- const dbName = this.getDBName(relation.envToken);
149
- const key = `${relation.hostUuid}@${this.getDBName(relation.envToken)}`;
150
- if (this.connections.has(key)) return this.connections.get(key);
151
- const connection = await this.createConnection(relation.hostUuid, dbName);
152
- if (connection) {
153
- this.log(`✅ Connected ${dbName} database sucessfully`, 'success');
154
- this.connections.set(key, connection);
155
- return connection;
156
- }
157
- }
158
- getDBName(envToken) {
159
- return `${_app.Core.settings.getDatabase().service.database}_${envToken}`;
160
- }
161
-
162
- //#Connection
163
- reconnect(db, attempts = 2) {
164
- db.sync().then(() => {
165
- this.log('Database pronto', 'success');
166
- }).catch(reason => {
167
- this.log('Attemping to connect master database', 'warning');
168
- (0, _logger.default)().warn('Erro ao inicializar o banco de dados, tentando novamente...', reason);
169
- if (attempts > 0) {
170
- setTimeout(() => this.reconnect(db, attempts - 1), 5000);
171
- } else {
172
- new _error.ApplicationException('Error on connecting master database', reason);
173
- }
174
- });
175
- }
176
- async createConnection(hostUuid, database) {
177
- const host = await _DatabaseHost.DatabaseHost.findByPk(hostUuid);
178
- if (!host) {
179
- this.log('createConnection:: Database host information not found: ' + hostUuid);
180
- return false;
181
- }
182
- const key = await _security.default.singleton().loadKeyByStr(host.credential);
183
- const data = await _security.default.singleton().verifySignature(host.password, key);
184
- if (!data) {
185
- this.log('createConnection::Error on decript password by credential: ' + hostUuid, 'danger');
186
- return false;
187
- }
188
- const password = data.payload;
189
- const queryHost = host.host.split(':');
190
- const sequelize = new _sequelize.Sequelize({
191
- host: queryHost[0],
192
- port: Number(queryHost[1]),
193
- dialect: host.dialect,
194
- database,
195
- username: host.username,
196
- password: password,
197
- define: {
198
- timestamps: true
199
- },
200
- timezone: '-03:00',
201
- logging(sql, timing) {
202
- (0, _logger.default)().trace('DATABASE', sql, timing);
203
- }
204
- });
205
- return new Promise((resolve, reject) => {
206
- sequelize.authenticate().then(async () => {
207
- resolve(sequelize);
208
- }).catch(reason => {
209
- reject(reason);
210
- });
211
- });
212
- }
213
- async testConnection(data) {
214
- const sequelize = new _sequelize.Sequelize({
215
- host: data.host,
216
- port: data.port,
217
- username: data.username,
218
- password: data.password,
219
- dialect: data.dialect,
220
- timezone: '-03:00',
221
- logging(sql, timing) {
222
- (0, _logger.default)().trace('DATABASE', sql, timing);
223
- }
224
- });
225
- return new Promise(resolve => {
226
- sequelize.authenticate().then(async () => {
227
- resolve(true);
228
- }).catch(reason => {
229
- new _error.ApplicationException('teste de conexão falhou', reason);
230
- resolve(false);
231
- }).finally(() => {
232
- sequelize.close();
233
- });
234
- });
235
- }
236
-
237
- //# Common
238
- async getRelation(tenantId) {
239
- let relation;
240
- /* fetch relation */
241
- if (this.relations.get(tenantId)) {
242
- relation = this.relations.get(tenantId);
243
- } else {
244
- relation = await _models.EnvDBHost.findOne({
245
- where: {
246
- envUuid: tenantId
247
- }
248
- });
249
- if (relation) {
250
- this.relations.set(tenantId, relation);
251
- }
252
- }
253
- return relation;
254
- }
255
-
256
- // #Entity
257
- async getModel(model, tenantId) {
258
- try {
259
- let connection = false;
260
- const modelKey = `${tenantId}#${model.name}`;
261
- if (tenantId == _app.Core.settings.getDatabase().service.database) {
262
- connection = _database.serviceDB;
263
- } else if (tenantId == _app.Core.settings.getDatabase().master.database) {
264
- connection = _database.masterDB;
265
- } else {
266
- connection = await this.getDB(tenantId);
267
- }
268
- if (this.initializedModels.has(modelKey)) return this.initializedModels.get(modelKey);
269
- if (!connection) {
270
- throw new Error('Conexão não encontrada');
271
- }
272
- const m = model.initialize(connection);
273
- await m.sync();
274
- this.initializedModels.set(modelKey, m);
275
- return m;
276
- } catch (error) {
277
- throw new _app.ErrorHandler('Erro ao obter o model', error);
278
- }
279
- }
280
- registerModels(models) {
281
- this.models = models;
282
- }
283
- }
284
- var _default = exports.default = SequelizeService;
@@ -1,56 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _controller = require("../app/controller");
8
- var _service = _interopRequireDefault(require("../app/service"));
9
- var _socket = require("socket.io");
10
- var _express = _interopRequireDefault(require("./express"));
11
- var _error = require("./error");
12
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
13
- /**
14
- * Serviço de gerênciamento de comunicação WS/WSS Socket
15
- *
16
- * @class SocketIOService
17
- * @extends {Service}
18
- * @implements {IService}
19
- */
20
- class SocketIOService extends _service.default {
21
- server;
22
- mainRouter;
23
- constructor() {
24
- super();
25
- }
26
- async init() {
27
- if (!this.mainRouter) throw new _error.ApplicationException('Need router'); //!sem router
28
- const server = _express.default.singleton().getHttpServer();
29
- this.createSocket(server);
30
- this.server.on('connection', this.onConnection.bind(this));
31
- this.log('Socket server created');
32
- }
33
- onConnection(socket) {
34
- this.log(`${socket.id} conectado`);
35
- socket.on('disconnect', () => this.log(`${socket.id} desconectado`));
36
- this.bindEvents(socket);
37
- }
38
- bindEvents(socket) {
39
- Object.entries(this.mainRouter).forEach(([key, handle]) => {
40
- socket.on(key, (...args) => {
41
- handle(new _controller.SocketRequest(socket, key), ...args);
42
- });
43
- });
44
- }
45
- createSocket(app, cors = {
46
- origin: '*'
47
- }) {
48
- this.server = new _socket.Server(app, {
49
- cors
50
- });
51
- }
52
- registerRouter(router) {
53
- this.mainRouter = router;
54
- }
55
- }
56
- var _default = exports.default = SocketIOService;
@@ -1,165 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.TaskSchedulingService = exports.TaskQueueService = exports.SchedulingTask = exports.QueueTask = void 0;
7
- var _bullmq = require("bullmq");
8
- var _fs = require("fs");
9
- var _nodeSchedule = require("node-schedule");
10
- var _service = _interopRequireDefault(require("../app/service"));
11
- var _singleton = _interopRequireDefault(require("../app/singleton"));
12
- var _error = require("./error");
13
- var _app = require("../app");
14
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
15
- //* Base
16
- class TaskServiceBase extends _service.default {
17
- jobsPath;
18
- setTaskPath(path) {
19
- this.jobsPath = path;
20
- }
21
- }
22
-
23
- //* Scheduler
24
- class TaskSchedulingService extends TaskServiceBase {
25
- jobs;
26
- async init() {
27
- if (!this.jobsPath) {
28
- return this.log('Tasks file path not found!', 'danger');
29
- }
30
- this.jobs = [];
31
- this.log('Initializing jobs...', 'info');
32
- await this.importAllJobs();
33
- await this.processAllJobs();
34
- this.log('All jobs initializeds...', 'info');
35
- }
36
- async registerJob(job) {
37
- this.jobs.push(job);
38
- }
39
- async importAllJobs() {
40
- if (!(0, _fs.existsSync)(this.jobsPath)) (0, _fs.mkdirSync)(this.jobsPath, {
41
- recursive: true
42
- });
43
- for (const handlerFile of (0, _fs.readdirSync)(this.jobsPath)) {
44
- try {
45
- const job = require(`${this.jobsPath}/${handlerFile}`).default;
46
- const jobInstance = job.singleton();
47
- this.jobs.push(jobInstance);
48
- } catch (error) {
49
- new _error.ApplicationException(`Falha ao iniciar um ou mais jobs: ${handlerFile}`, error);
50
- }
51
- }
52
- }
53
- async processAllJobs() {
54
- for (const job of this.jobs) {
55
- if (!job.getActive()) continue;
56
- (0, _nodeSchedule.scheduleJob)(job.getJobTime(), job.handler.bind(job));
57
- this.log(`Job '${job.getJobName()}' started...`, 'warning');
58
- }
59
- }
60
- }
61
- exports.TaskSchedulingService = TaskSchedulingService;
62
- class SchedulingTask extends _singleton.default {
63
- getJobTime() {
64
- return this.cron;
65
- }
66
- getActive() {
67
- return this.active;
68
- }
69
- getJobName() {
70
- return this.name;
71
- }
72
- }
73
-
74
- //* Queue
75
- exports.SchedulingTask = SchedulingTask;
76
- class TaskQueueService extends TaskServiceBase {
77
- jobs;
78
- connection;
79
- async init() {
80
- this.jobs = [];
81
- this.connection = {
82
- host: _app.Core.settings.getCache().host,
83
- port: Number(_app.Core.settings.getCache().port),
84
- password: _app.Core.settings.getCache().password
85
- };
86
- this.log('Initializing jobs...', 'info');
87
- await this.importAllJobs();
88
- await this.processAllJobs();
89
- this.log('All jobs initializeds...', 'info');
90
- }
91
- async registerJob(job) {
92
- this.jobs.push(job);
93
- }
94
- async importAllJobs() {
95
- if (!(0, _fs.existsSync)(this.jobsPath)) (0, _fs.mkdirSync)(this.jobsPath, {
96
- recursive: true
97
- });
98
- for (const handlerFile of (0, _fs.readdirSync)(this.jobsPath)) {
99
- const job = require(`${this.jobsPath}/${handlerFile}`).default;
100
- const jobInstance = job.singleton();
101
- this.jobs.push(jobInstance);
102
- }
103
- }
104
- async processAllJobs() {
105
- for (const job of this.jobs) {
106
- this.startTask(job);
107
- }
108
- }
109
- async startTask(task) {
110
- if (!task.getActive()) return;
111
- const queue = new _bullmq.Queue(task.getQueueName(), {
112
- connection: this.connection
113
- });
114
- const worker = new _bullmq.Worker(task.getQueueName(), task.handle.bind(task), {
115
- connection: this.connection
116
- });
117
- task.setQueue(queue);
118
- task.setWorker(worker);
119
- task.init();
120
- this.log(`Job '${task.getQueueName()}' started...`, 'warning');
121
- }
122
- }
123
- exports.TaskQueueService = TaskQueueService;
124
- class QueueTask extends _singleton.default {
125
- queue;
126
- worker;
127
- initialize() {
128
- this.queue = new _bullmq.Queue(this.getQueueName(), {
129
- // Configurações do Redis
130
- connection: {
131
- host: 'localhost',
132
- port: 6379
133
- }
134
- });
135
- this.worker = new _bullmq.Worker(this.getQueueName(), this.handle.bind(this), {
136
- connection: {
137
- host: 'localhost',
138
- port: 6379
139
- }
140
- });
141
- }
142
- async addJob(data) {
143
- await this.queue.add(this.getQueueName(), data);
144
- this.log('Nova tarefa disponível.', 'comment');
145
- }
146
- getQueue() {
147
- return this.queue;
148
- }
149
- setQueue(queue) {
150
- this.queue = queue;
151
- }
152
- getWorker() {
153
- return this.worker;
154
- }
155
- setWorker(worker) {
156
- this.worker = worker;
157
- }
158
- getActive() {
159
- return this.active;
160
- }
161
- getQueueName() {
162
- return this.queueName;
163
- }
164
- }
165
- exports.QueueTask = QueueTask;
package/lib/utils/api.js DELETED
@@ -1,50 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _core = _interopRequireDefault(require("../app/core"));
8
- var _error = require("../services/error");
9
- var _axios = _interopRequireDefault(require("axios"));
10
- var _dateFns = require("date-fns");
11
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
12
- class Api extends _core.default {
13
- axios;
14
- constructor() {
15
- super();
16
- this.init();
17
- }
18
- async init() {
19
- this.axios = _axios.default.create({
20
- baseURL: this.host,
21
- headers: {
22
- ...this.headers,
23
- 'Content-Type': 'application/json'
24
- },
25
- validateStatus: this.validateStatus
26
- });
27
- }
28
- async request(endpoint, method, data, params, headers) {
29
- try {
30
- const res = await this.axios({
31
- method,
32
- url: this.host + endpoint,
33
- data,
34
- params,
35
- headers: {
36
- ...headers,
37
- ...this.headers
38
- }
39
- });
40
- return res.data;
41
- } catch (error) {
42
- new _error.ApplicationException('não foi possível realizar uma requisição', error);
43
- }
44
- }
45
- getLogicalSecurityId() {
46
- const date = (0, _dateFns.format)(new Date(), 'yyyy-MM-dd');
47
- return String(Date.parse(date) - 5000);
48
- }
49
- }
50
- var _default = exports.default = Api;
@@ -1,157 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.masterDB = void 0;
7
- exports.processFilters = processFilters;
8
- exports.serviceDB = void 0;
9
- var _sequelize = require("sequelize");
10
- var _app = require("../app");
11
- var _logger = _interopRequireDefault(require("./logger"));
12
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
13
- const serviceDB = exports.serviceDB = new _sequelize.Sequelize({
14
- database: _app.Core.settings.getDatabase().service.database,
15
- dialect: _app.Core.settings.getDatabase().master.dialect,
16
- username: _app.Core.settings.getDatabase().master.username,
17
- password: _app.Core.settings.getDatabase().master.password,
18
- define: {
19
- timestamps: true
20
- },
21
- timezone: '-03:00',
22
- logging(sql, timing) {
23
- (0, _logger.default)().trace('DATABASE', sql, timing);
24
- }
25
- });
26
- const masterDB = exports.masterDB = new _sequelize.Sequelize({
27
- database: _app.Core.settings.getDatabase().master.database,
28
- dialect: _app.Core.settings.getDatabase().master.dialect,
29
- username: _app.Core.settings.getDatabase().master.username,
30
- password: _app.Core.settings.getDatabase().master.password,
31
- define: {
32
- timestamps: true
33
- },
34
- timezone: '-03:00',
35
- logging(sql, timing) {
36
- (0, _logger.default)().trace('DATABASE', sql, timing);
37
- }
38
- });
39
- function processCondition(cond) {
40
- if ('or' in cond) {
41
- return {
42
- [_sequelize.Op.or]: cond.or.map(subCond => processCondition(subCond))
43
- };
44
- }
45
- if ('and' in cond) {
46
- return {
47
- [_sequelize.Op.and]: cond.and.map(subCond => processCondition(subCond))
48
- };
49
- }
50
- const simpleWhere = {};
51
- if (cond.eq !== undefined) {
52
- simpleWhere[_sequelize.Op.eq] = cond.type === 'DATE' ? new Date(cond.eq) : cond.eq;
53
- }
54
- if (cond.gt !== undefined) {
55
- simpleWhere[_sequelize.Op.gt] = cond.type === 'DATE' ? new Date(cond.eq) : cond.gt;
56
- }
57
- if (cond.lt !== undefined) {
58
- simpleWhere[_sequelize.Op.lt] = cond.type === 'DATE' ? new Date(cond.lt) : cond.lt;
59
- }
60
- if (cond.between !== undefined) {
61
- simpleWhere[_sequelize.Op.between] = cond.type === 'DATE' ? cond.between.map(d => new Date(d)) : cond.between;
62
- }
63
- if (cond.notBetween !== undefined) {
64
- simpleWhere[_sequelize.Op.notBetween] = cond.type === 'DATE' ? cond.notBetween.map(d => new Date(d)) : cond.notBetween;
65
- }
66
- if (cond.like !== undefined) {
67
- simpleWhere[_sequelize.Op.like] = cond.type === 'DATE' ? new Date(cond.like) : cond.like;
68
- }
69
- if (cond.notLike !== undefined) {
70
- simpleWhere[_sequelize.Op.notLike] = cond.type === 'DATE' ? new Date(cond.notLike) : cond.notLike;
71
- }
72
- if (cond.in !== undefined) {
73
- simpleWhere[_sequelize.Op.in] = cond.type === 'DATE' ? cond.in.map(d => new Date(d)) : cond.in;
74
- }
75
- if (cond.notIn !== undefined) {
76
- simpleWhere[_sequelize.Op.notIn] = cond.type === 'DATE' ? cond.notIn.map(d => new Date(d)) : cond.notIn;
77
- }
78
- return simpleWhere;
79
- }
80
- function processDateCondition(key, cond) {
81
- const simpleWhere = [key, undefined];
82
- if (cond.eq !== undefined) {
83
- simpleWhere[0] = _sequelize.Op.and;
84
- simpleWhere[1] = [(0, _sequelize.literal)(`DATE(${key}) = '${cond.eq}'`)];
85
- }
86
- if (cond.gt !== undefined) {
87
- simpleWhere[0] = _sequelize.Op.and;
88
- simpleWhere[1] = [(0, _sequelize.literal)(`DATE(${key}) > '${cond.gt}'`)];
89
- }
90
- if (cond.lt !== undefined) {
91
- simpleWhere[0] = _sequelize.Op.and;
92
- simpleWhere[1] = [(0, _sequelize.literal)(`DATE(${key}) < '${cond.lt}'`)];
93
- }
94
- if (cond.between !== undefined) {
95
- simpleWhere[1] = {
96
- [_sequelize.Op.between]: cond.between.map(d => new Date(d))
97
- };
98
- }
99
- if (cond.notBetween !== undefined) {
100
- simpleWhere[1] = {
101
- [_sequelize.Op.notBetween]: cond.notBetween.map(d => new Date(d))
102
- };
103
- }
104
- if (cond.in !== undefined) {
105
- simpleWhere[1] = {
106
- [_sequelize.Op.in]: cond.in.map(d => new Date(d))
107
- };
108
- }
109
- if (cond.notIn !== undefined) {
110
- simpleWhere[1] = {
111
- [_sequelize.Op.notIn]: cond.notIn.map(d => new Date(d))
112
- };
113
- }
114
- return simpleWhere;
115
- }
116
-
117
- // Função Principal para Processar Filtros
118
- function processFilters(filters) {
119
- if (!filters) return {};
120
- const where = {};
121
- Object.entries(filters).forEach(([key, condition]) => {
122
- if (key === 'or' || key === 'and') {
123
- const logicalOp = key === 'or' ? _sequelize.Op.or : _sequelize.Op.and;
124
- const t = [];
125
- for (const c of condition) {
126
- const [[key, value]] = Object.entries(c);
127
- t.push({
128
- [key]: processCondition(value)
129
- });
130
- }
131
- if (!where[logicalOp]) {
132
- where[logicalOp] = [];
133
- }
134
- where[logicalOp].push(...t);
135
- } else {
136
- const field = key;
137
- const isDate = condition.type && condition.type === 'DATE';
138
- const isTime = condition.type && condition.type === 'TIME';
139
- const isDateTime = condition.type && condition.type === 'DATETIME';
140
- if (isDate) {
141
- const [k, c] = processDateCondition(key, condition);
142
- where[k] = c;
143
- } else {
144
- const processedCondition = processCondition(condition);
145
- if (where[field]) {
146
- where[field] = {
147
- ...where[field],
148
- ...processedCondition
149
- };
150
- } else {
151
- where[field] = processedCondition;
152
- }
153
- }
154
- }
155
- });
156
- return where;
157
- }