delore-crm-core 1.0.12 → 1.0.14

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.
@@ -1,93 +1,158 @@
1
- const Sequelize = require('sequelize');
2
- const logger = require('../utils/logger.js');
3
- const authControl = require('../auth/auth.control.js');
1
+ const Sequelize = require("sequelize");
2
+ const logger = require("../utils/logger.js");
3
+ const authControl = require("../auth/auth.control.js");
4
4
  let sequelize = null;
5
5
 
6
- const { MongoClient } = require('mongodb');
6
+ const { MongoClient } = require("mongodb");
7
7
 
8
8
  const uri = process.env.MONGODB_URI;
9
9
  const client = new MongoClient(uri);
10
10
  var db = null;
11
11
 
12
+ function envInt(name, defaultValue) {
13
+ const value = Number.parseInt(process.env[name], 10);
14
+ return Number.isNaN(value) ? defaultValue : value;
15
+ }
16
+
12
17
  async function connectMongoDB() {
13
- try {
14
- await client.connect();
15
- db = client.db('sessions');
16
- logger.info('mongoDB - - > Conectado ao MongoDB!');
17
- if (db) {
18
- await authControl.loadAllSecretToMemory(db);
19
- }
20
- } catch (error) {
21
- logger.error('mongoDB - - > Erro ao conectar:', error.message);
22
- }
18
+ try {
19
+ await client.connect();
20
+ db = client.db("sessions");
21
+ logger.info("mongoDB - - > Conectado ao MongoDB!");
22
+ if (db) {
23
+ await authControl.loadAllSecretToMemory(db);
24
+ }
25
+ } catch (error) {
26
+ logger.error("mongoDB - - > Erro ao conectar:", error.message);
27
+ }
23
28
  }
24
29
 
25
30
  module.exports = {
26
- getMongoDB: function () {
27
- return db;
28
- },
29
- getSequelize: function () {
30
- return sequelize;
31
- },
32
- init(onConnect) {
33
- sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASS, {
34
- dialect: 'mysql',
35
- host: process.env.DB_HOST,
36
- pool: {
37
- max: 400, // Aumentar o limite máximo de conexões se o tráfego for alto
38
- min: 20, // Manter um número mínimo de conexões ativas
39
- idle: 10000, // Tempo que uma conexão pode ficar ociosa (30 segundos)
40
- acquire: 60000, // Tempo máximo para aguardar uma conexão do pool (60 segundos)
41
- evict: 30000, // Remover conexões ociosas após 30 segundos
42
- },
43
- timezone: '-03:00',
44
- dialectOptions: {
45
- multipleStatements: true,
46
- },
47
- define: {
48
- underscored: false,
49
- freezeTableName: true,
50
- charset: 'utf8',
51
- timestamps: false,
52
- createdAt: false,
53
- updatedAt: false,
54
- hooks: {
55
- beforeValidate: async (model, options) => {
56
- var models = sequelize.models;
57
- var modelOriginal = models[model.constructor.name];
58
- for (const key in options.fields) {
59
- const field = options.fields[key];
60
- if (modelOriginal && modelOriginal.fieldRawAttributesMap[field] && modelOriginal.fieldRawAttributesMap[field].type.constructor.key == 'DATEONLY') {
61
- if (model[field] === '') {
62
- model[field] = null;
63
- }
64
- }
65
- if (modelOriginal && modelOriginal.fieldRawAttributesMap[field] && modelOriginal.fieldRawAttributesMap[field].type.constructor.key == 'DATE') {
66
- if (model[field] === '') {
67
- model[field] = null;
68
- }
69
- }
31
+ getMongoDB: function () {
32
+ return db;
33
+ },
34
+ getSequelize: function () {
35
+ return sequelize;
36
+ },
37
+ init(onConnect) {
38
+ let isolationLevel =
39
+ process.env.DB_ISOLATION === "REPEATABLE_READ"
40
+ ? Sequelize.Transaction.ISOLATION_LEVELS.REPEATABLE_READ
41
+ : Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED;
42
+ const lockWaitTimeout = envInt("DB_LOCK_WAIT_TIMEOUT", 15);
43
+
44
+ logger.info("init - - > Iniciando conexão com o MySQL..." + isolationLevel);
45
+
46
+ sequelize = new Sequelize(
47
+ process.env.DB_DATABASE,
48
+ process.env.DB_USER,
49
+ process.env.DB_PASS,
50
+ {
51
+ dialect: "mysql",
52
+ host: process.env.DB_HOST,
53
+ pool: {
54
+ max: envInt("DB_POOL_MAX", 30),
55
+ min: envInt("DB_POOL_MIN", 0),
56
+ idle: envInt("DB_POOL_IDLE", 10000),
57
+ acquire: envInt("DB_POOL_ACQUIRE", 30000),
58
+ evict: envInt("DB_POOL_EVICT", 10000),
59
+ },
60
+ timezone: "-03:00",
61
+ dialectOptions: {
62
+ multipleStatements: true,
63
+ },
64
+ retry: {
65
+ max: envInt("DB_RETRY_MAX", 3),
66
+ match: [
67
+ /Deadlock/i,
68
+ /ER_LOCK_DEADLOCK/,
69
+ /ER_LOCK_WAIT_TIMEOUT/,
70
+ /Lock wait timeout exceeded/i,
71
+ ],
72
+ backoffBase: envInt("DB_RETRY_BACKOFF_BASE", 100),
73
+ backoffExponent: 1.5,
74
+ },
75
+ hooks: {
76
+ afterConnect: async (connection) => {
77
+ const query = (sql) =>
78
+ new Promise((resolve, reject) => {
79
+ connection.query(sql, (error) => {
80
+ if (error) reject(error);
81
+ else resolve();
82
+ });
83
+ });
84
+
85
+ await query(
86
+ `SET SESSION TRANSACTION ISOLATION LEVEL ${isolationLevel.replace(
87
+ "_",
88
+ " ",
89
+ )}`,
90
+ );
91
+ await query(
92
+ `SET SESSION innodb_lock_wait_timeout = ${lockWaitTimeout}`,
93
+ );
94
+ },
95
+ },
96
+ define: {
97
+ underscored: false,
98
+ freezeTableName: true,
99
+ charset: "utf8",
100
+ timestamps: false,
101
+ createdAt: false,
102
+ updatedAt: false,
103
+ hooks: {
104
+ beforeValidate: async (model, options) => {
105
+ var models = sequelize.models;
106
+ var modelOriginal = models[model.constructor.name];
107
+ for (const key in options.fields) {
108
+ const field = options.fields[key];
109
+ if (
110
+ modelOriginal &&
111
+ modelOriginal.fieldRawAttributesMap[field] &&
112
+ modelOriginal.fieldRawAttributesMap[field].type.constructor
113
+ .key == "DATEONLY"
114
+ ) {
115
+ if (model[field] === "") {
116
+ model[field] = null;
117
+ }
118
+ }
119
+ if (
120
+ modelOriginal &&
121
+ modelOriginal.fieldRawAttributesMap[field] &&
122
+ modelOriginal.fieldRawAttributesMap[field].type.constructor
123
+ .key == "DATE"
124
+ ) {
125
+ if (model[field] === "") {
126
+ model[field] = null;
70
127
  }
71
- },
128
+ }
129
+ }
72
130
  },
73
- },
74
- isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
75
- logging: (sql) => logger.info(sql),
76
- });
131
+ },
132
+ },
133
+ isolationLevel: isolationLevel,
134
+ logging: (sql) => logger.trace(sql),
135
+ },
136
+ );
77
137
 
78
- sequelize
79
- .authenticate()
80
- .then(async () => {
81
- //
82
- // Após conectar ao MySQL, conecta ao MongoDB
83
- //
84
- await connectMongoDB();
138
+ sequelize
139
+ .authenticate()
140
+ .then(async () => {
141
+ //
142
+ // Após conectar ao MySQL, conecta ao MongoDB
143
+ //
144
+ await connectMongoDB();
85
145
 
86
- logger.info('MySQL and MongoDB - - > Connection has been established successfully.');
87
- onConnect();
88
- })
89
- .catch((err) => {
90
- logger.error('MySQL and MongoDB - - > Unable to connect to the database:' + err.message);
91
- });
92
- },
146
+ logger.info(
147
+ "MySQL and MongoDB - - > Connection has been established successfully.",
148
+ );
149
+ onConnect();
150
+ })
151
+ .catch((err) => {
152
+ logger.error(
153
+ "MySQL and MongoDB - - > Unable to connect to the database:" +
154
+ err.message,
155
+ );
156
+ });
157
+ },
93
158
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "delore-crm-core",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
4
4
  "description": "Core CRM utilities for Delore projects",
5
5
  "main": "index.js",
6
6
  "type": "commonjs",
package/utils/logger.js CHANGED
@@ -1,63 +1,74 @@
1
- const pretty = require('pino-pretty');
1
+ const pretty = require("pino-pretty");
2
2
 
3
3
  const stream = pretty({
4
- levelFirst: true,
5
- colorize: true,
6
- ignore: 'pid,hostname',
7
- translateTime: 'yyyy-mm-dd HH:MM:ss.l',
4
+ levelFirst: true,
5
+ colorize: true,
6
+ ignore: "pid,hostname",
7
+ translateTime: "yyyy-mm-dd HH:MM:ss.l",
8
8
  });
9
9
 
10
- const pino = require('pino')(stream);
10
+ const pino = require("pino")(stream);
11
11
 
12
- pino.level = process.env.PINO_LOG_LEVEL || 'fatal';
12
+ pino.level = process.env.PINO_LOG_LEVEL || "info";
13
13
 
14
14
  exports = module.exports = {
15
-
16
- setLevel(level) {
17
- pino.level = level || 'fatal';
18
- },
19
-
20
- getPino() {
21
- return pino;
22
- },
23
-
24
- info(message) {
25
- pino.info(message);
26
- },
27
-
28
- info(mensagem, fileName, methodName) {
29
- pino.info({ fileName, methodName }, mensagem);
30
- },
31
-
32
- debug(message) {
33
- pino.debug(message);
34
- },
35
-
36
- debug(mensagem, fileName, methodName) {
37
- pino.debug({ fileName, methodName }, mensagem);
38
- },
39
-
40
- warn(message) {
41
- pino.warn(message);
42
- },
43
-
44
- warn(mensagem, fileName, methodName) {
45
- pino.warn({ fileName, methodName }, mensagem);
46
- },
47
-
48
- error(message) {
49
- pino.error(message);
50
- },
51
-
52
- error(error, fileName, methodName) {
53
- pino.error({ error: error.stack || error.message || error, fileName, methodName });
54
- },
55
-
56
- fatal(message) {
57
- pino.fatal(message);
58
- },
59
-
60
- fatal(mensagem, fileName, methodName) {
61
- pino.fatal({ fileName, methodName }, mensagem);
62
- },
15
+ setLevel(level) {
16
+ pino.level = level || "info";
17
+ },
18
+
19
+ getPino() {
20
+ return pino;
21
+ },
22
+
23
+ info(message) {
24
+ pino.info(message);
25
+ },
26
+
27
+ info(mensagem, fileName, methodName) {
28
+ pino.info({ fileName, methodName }, mensagem);
29
+ },
30
+
31
+ debug(message) {
32
+ pino.debug(message);
33
+ },
34
+
35
+ debug(mensagem, fileName, methodName) {
36
+ pino.debug({ fileName, methodName }, mensagem);
37
+ },
38
+
39
+ warn(message) {
40
+ pino.warn(message);
41
+ },
42
+
43
+ warn(mensagem, fileName, methodName) {
44
+ pino.warn({ fileName, methodName }, mensagem);
45
+ },
46
+
47
+ error(message) {
48
+ pino.error(message);
49
+ },
50
+
51
+ error(error, fileName, methodName) {
52
+ pino.error({
53
+ error: error.stack || error.message || error,
54
+ fileName,
55
+ methodName,
56
+ });
57
+ },
58
+
59
+ fatal(message) {
60
+ pino.fatal(message);
61
+ },
62
+
63
+ fatal(mensagem, fileName, methodName) {
64
+ pino.fatal({ fileName, methodName }, mensagem);
65
+ },
66
+
67
+ trace(message) {
68
+ pino.trace(message);
69
+ },
70
+
71
+ trace(mensagem, fileName, methodName) {
72
+ pino.trace({ fileName, methodName }, mensagem);
73
+ },
63
74
  };