badmfck-api-server 5.0.16 → 6.0.1

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 (33) hide show
  1. package/README.md +824 -0
  2. package/dist/apiServer/APIService.d.ts +16 -4
  3. package/dist/apiServer/APIService.js +92 -3
  4. package/dist/apiServer/DBService.js +1 -2
  5. package/dist/apiServer/WebSocketServer.d.ts +39 -0
  6. package/dist/apiServer/WebSocketServer.js +173 -0
  7. package/dist/apiServer/db/MysqlAdapter.d.ts +4 -0
  8. package/dist/apiServer/db/MysqlAdapter.js +93 -84
  9. package/dist/apiServer/db/PostgresAdapter.d.ts +10 -3
  10. package/dist/apiServer/deployment/NginxHelper.d.ts +1 -1
  11. package/dist/apiServer/deployment/NginxHelper.js +3 -0
  12. package/dist/apiServer/monitor/AccessStore.d.ts +24 -0
  13. package/dist/apiServer/monitor/AccessStore.js +146 -0
  14. package/dist/apiServer/monitor/Monitor.js +5 -4
  15. package/dist/apiServer/monitor/MonitorAuth.d.ts +11 -1
  16. package/dist/apiServer/monitor/MonitorAuth.js +157 -31
  17. package/dist/apiServer/monitor/index.html +3 -3
  18. package/dist/index.d.ts +12 -2
  19. package/dist/index.js +27 -3
  20. package/monitoring.help.md +1 -1
  21. package/package.json +2 -2
  22. package/dist/apiServer/MysqlService.d.ts +0 -123
  23. package/dist/apiServer/MysqlService.js +0 -817
  24. package/dist/apiServer/WSAPITransport.d.ts +0 -0
  25. package/dist/apiServer/WSAPITransport.js +0 -1
  26. package/dist/apiServer/WebSocketHandler.d.ts +0 -0
  27. package/dist/apiServer/WebSocketHandler.js +0 -1
  28. package/dist/apiServer/WebsocketServerService.d.ts +0 -9
  29. package/dist/apiServer/WebsocketServerService.js +0 -18
  30. package/dist/apiServer/deployment/Deployment.d.ts +0 -10
  31. package/dist/apiServer/deployment/Deployment.js +0 -24
  32. package/dist/apiServer/interceptors/IntHmacSha256.d.ts +0 -5
  33. package/dist/apiServer/interceptors/IntHmacSha256.js +0 -22
@@ -1,817 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.MysqlService = exports.isMysqlError = exports.executeQuery = exports.DEPRECATED_REQ_MYSQL_TROLLBACK = exports.DEPRECATED_REQ_MYSQL_TCOMMIT = exports.DEPRECATED_REQ_MYSQL_TQUERY = exports.DEPRECATED_REQ_MYSQL_TBEGIN = exports.DEPRECATED_REQ_MYSQL_QUERY = exports.DEPRECATED_S_MYSQL_STARTED = void 0;
40
- const BaseService_1 = require("./BaseService");
41
- const badmfck_signal_1 = __importStar(require("badmfck-signal"));
42
- const crypto_1 = require("crypto");
43
- const LogService_1 = require("./LogService");
44
- const mysql = __importStar(require("mysql2/promise"));
45
- const fs_1 = __importDefault(require("fs"));
46
- const path_1 = __importDefault(require("path"));
47
- exports.DEPRECATED_S_MYSQL_STARTED = new badmfck_signal_1.default();
48
- exports.DEPRECATED_REQ_MYSQL_QUERY = new badmfck_signal_1.Req(undefined, "REQ_MYSQL_QUERY");
49
- exports.DEPRECATED_REQ_MYSQL_TBEGIN = new badmfck_signal_1.Req(undefined, "REQ_MYSQL_TRANSACTION_BEGING");
50
- exports.DEPRECATED_REQ_MYSQL_TQUERY = new badmfck_signal_1.Req(undefined, "REQ_MYSQL_TRANSACTION_ADD_OPERATION");
51
- exports.DEPRECATED_REQ_MYSQL_TCOMMIT = new badmfck_signal_1.Req(undefined, "REQ_MYSQL_TCOMMIT");
52
- exports.DEPRECATED_REQ_MYSQL_TROLLBACK = new badmfck_signal_1.Req(undefined, "REQ_MYSQL_TROLLBACK");
53
- const executeQuery = async (query) => { return await exports.DEPRECATED_REQ_MYSQL_QUERY.request(query); };
54
- exports.executeQuery = executeQuery;
55
- const isMysqlError = (e) => {
56
- return e.code !== undefined && e.errno !== undefined && e.sql !== undefined && e.name !== undefined && e.message !== undefined;
57
- };
58
- exports.isMysqlError = isMysqlError;
59
- class MysqlService extends BaseService_1.BaseService {
60
- reconnectionTimeout = 1000 * 3;
61
- reconnecting = false;
62
- pool = null;
63
- options;
64
- serviceStarted = false;
65
- timeoutID;
66
- debug = false;
67
- queries = [];
68
- static nextTransactionID = 1;
69
- transactions = [];
70
- maxTransactionWaitTime = 1000 * 60 * 1;
71
- lastSuccessQueryTime = 0;
72
- pingInterval = 1000 * 60 * 5;
73
- failReportFileStream = null;
74
- failReportFileStreamName = null;
75
- failReportLastAccessTime = 0;
76
- constructor(options) {
77
- super("mysql");
78
- this.options = options;
79
- if (this.options.host.startsWith("_"))
80
- this.options.host = decrypt(this.options.host.substring(1)) ?? this.options.host;
81
- if (this.options.user.startsWith("_"))
82
- this.options.user = decrypt(this.options.user.substring(1)) ?? this.options.user;
83
- if (this.options.database.startsWith("_"))
84
- this.options.database = decrypt(this.options.database.substring(1)) ?? this.options.database;
85
- if (this.options.password.startsWith("_"))
86
- this.options.password = decrypt(this.options.password.substring(1)) ?? this.options.password;
87
- if (this.options.debug)
88
- this.debug = true;
89
- if (this.options.naxTransactionWaitTime)
90
- this.maxTransactionWaitTime = this.options.naxTransactionWaitTime;
91
- setInterval(() => {
92
- const now = Date.now();
93
- const count = this.transactions.length;
94
- const removedIDs = [];
95
- for (let i of this.transactions) {
96
- if (now - i.timestamp > this.maxTransactionWaitTime) {
97
- (0, LogService_1.logError)("Release transaction connection due to timeout");
98
- this.rollbackTransaction(i, true);
99
- removedIDs.push(i.id);
100
- }
101
- }
102
- this.transactions = this.transactions.filter(i => !removedIDs.includes(i.id));
103
- if (this.debug && count - this.transactions.length > 0)
104
- (0, LogService_1.logInfo)("Removed: ", count - this.transactions.length);
105
- if (Date.now() - this.lastSuccessQueryTime > this.pingInterval) {
106
- if (!this.pool)
107
- return;
108
- for (let i = 0; i < this.options.connectionLimit; i++) {
109
- exports.DEPRECATED_REQ_MYSQL_QUERY.request({ query: "SELECT 1 @NOLIMIT", fields: [] });
110
- if (this.debug)
111
- (0, LogService_1.logInfo)("Ping mysql on each connection in pool");
112
- }
113
- }
114
- }, 1000 * 30);
115
- setInterval(() => {
116
- if (!this.failReportFileStream)
117
- return;
118
- if (Date.now() - this.failReportLastAccessTime > 1000 * 60 * 15) {
119
- this.failReportFileStream.end();
120
- this.failReportFileStream = null;
121
- }
122
- }, 1000 * 60 * 5);
123
- if (options.transactionFailReportDir) {
124
- try {
125
- if (!fs_1.default.existsSync(options.transactionFailReportDir)) {
126
- fs_1.default.mkdirSync(options.transactionFailReportDir);
127
- }
128
- }
129
- catch (e) {
130
- options.transactionFailReportDir = undefined;
131
- (0, LogService_1.logCrit)("${MysqlService.js}", "Can't create transaction fail report dir");
132
- }
133
- }
134
- }
135
- static async executeQuery(query) { return await exports.DEPRECATED_REQ_MYSQL_QUERY.request(query); }
136
- async init() {
137
- super.init();
138
- process.on('SIGINT', async () => {
139
- await this.finishApp();
140
- process.exit(0);
141
- });
142
- process.on('SIGTERM', async () => {
143
- await this.finishApp();
144
- process.exit(0);
145
- });
146
- this.serviceStarted = false;
147
- let poolCreated = false;
148
- while (!poolCreated) {
149
- (0, LogService_1.logInfo)("${MysqlService.js}", "Connecting to MYSQL!");
150
- poolCreated = await this.recreatePool();
151
- if (!poolCreated) {
152
- (0, LogService_1.logCrit)("${MysqlService.js}", "Can't connect to MYSQL! Retrying in 3 seconds...");
153
- await new Promise((resolve) => setTimeout(resolve, 3000));
154
- }
155
- }
156
- exports.DEPRECATED_REQ_MYSQL_QUERY.listener = async (data) => {
157
- if (!Array.isArray(data))
158
- data = [data];
159
- const promises = [];
160
- for (let i of data) {
161
- const query = MysqlService.prepareQuery(i.query, i.fields);
162
- promises.push(this.execute(query, i.rollbackQuery ?? null, i.transactionID ?? 0, i.throwable ?? false, i.calculateCount ?? false));
163
- }
164
- if (this.debug) {
165
- (0, LogService_1.logInfo)("Execute queries: ", data.length);
166
- for (let i of data)
167
- (0, LogService_1.logInfo)(i);
168
- }
169
- const result = await Promise.all(promises);
170
- for (let i of result) {
171
- if (i.error && i.error.code === "CONN_ERR") {
172
- (0, LogService_1.logError)("Connection error, was destroyed, recreate pool");
173
- await this.recreatePool();
174
- }
175
- if (i.error && (i.error.fatal || i.error.throwable))
176
- throw i.error;
177
- if (!i.error)
178
- this.lastSuccessQueryTime = Date.now();
179
- }
180
- return result;
181
- };
182
- exports.DEPRECATED_REQ_MYSQL_TBEGIN.listener = async () => {
183
- const conn = await this.pool?.getConnection();
184
- if (!conn)
185
- return { code: "NO_POOL", errno: 100000, fatal: true, sql: "", name: "NO_POOL", message: "Mysql pool not created", throwable: false };
186
- for (let i of this.transactions) {
187
- if (i.conn === conn) {
188
- (0, LogService_1.logInfo)("Your connection is in transaction");
189
- return { code: "CONN_IN_TRX", errno: 100005, fatal: true, throwable: false, sql: "", name: "CONN_IN_TRX", message: "Connection is in transaction" };
190
- }
191
- }
192
- const tid = MysqlService.nextTransactionID++;
193
- if (this.debug)
194
- (0, LogService_1.logInfo)("Begin transaction with id ", tid);
195
- try {
196
- await conn.query("START TRANSACTION");
197
- if (this.debug)
198
- (0, LogService_1.logInfo)("Transaction started");
199
- }
200
- catch (e) {
201
- this.rollbackTransaction({ id: tid, conn: conn, timestamp: Date.now(), queries: [{ sql: "START TRANSACTION", status: "error" }] });
202
- return this.createMysqlQueryError(e);
203
- }
204
- this.transactions.push({
205
- id: tid,
206
- timestamp: Date.now(),
207
- conn: conn,
208
- queries: []
209
- });
210
- if (this.debug)
211
- (0, LogService_1.logInfo)("Transactions pool: ", this.transactions);
212
- return tid;
213
- };
214
- exports.DEPRECATED_REQ_MYSQL_TQUERY.listener = async (data) => {
215
- const trx = this.transactions.find(i => i.id === data.tid);
216
- if (!trx)
217
- return { err: {
218
- code: "NO_TRX",
219
- errno: 100004,
220
- fatal: true,
221
- sql: "",
222
- name: "NO_TRX",
223
- message: "Transaction not found",
224
- }, data: null, rollbackError: null, count: 0 };
225
- const query = MysqlService.prepareQuery(data.query.query, data.query.fields);
226
- let err = null;
227
- let sqlData = null;
228
- if (this.debug)
229
- (0, LogService_1.logInfo)("Execute query on transaction: ", trx.id);
230
- try {
231
- sqlData = await trx.conn.query(query);
232
- }
233
- catch (e) {
234
- err = this.createMysqlQueryError(e);
235
- }
236
- let count = 0;
237
- if (err)
238
- this.rollbackTransaction(trx);
239
- else {
240
- if (data.query.calculateCount && query.indexOf("SELECT") === 0) {
241
- let countQuery = this.prepareCountQuery(query);
242
- try {
243
- const countQueryResult = await trx.conn.query(countQuery);
244
- if (countQueryResult && countQueryResult.length > 0) {
245
- count = countQueryResult[0].count;
246
- }
247
- }
248
- catch (e) {
249
- (0, LogService_1.logError)("${MysqlService.js}->TQUERY->query error", e);
250
- }
251
- }
252
- }
253
- if (this.debug)
254
- (0, LogService_1.logInfo)("Query execution status:", err ? err.message : "completed");
255
- trx.queries.push({ sql: query, status: err ? err.message : "completed" });
256
- return {
257
- data: sqlData ? sqlData[0] : null,
258
- error: err,
259
- count: count
260
- };
261
- };
262
- exports.DEPRECATED_REQ_MYSQL_TROLLBACK.listener = async (tid) => {
263
- const trx = this.transactions.find(i => i.id === tid);
264
- if (!trx) {
265
- return {
266
- code: "NO_TRX",
267
- errno: 100004,
268
- fatal: true,
269
- throwable: false,
270
- sql: "",
271
- name: "NO_TRX",
272
- message: "Transaction not found"
273
- };
274
- }
275
- await this.rollbackTransaction(trx);
276
- return null;
277
- };
278
- exports.DEPRECATED_REQ_MYSQL_TCOMMIT.listener = async (tid) => {
279
- const trx = this.transactions.find(i => i.id === tid);
280
- if (!trx) {
281
- return {
282
- code: "NO_TRX",
283
- errno: 100004,
284
- fatal: true,
285
- sql: "",
286
- name: "NO_TRX",
287
- message: "Transaction not found",
288
- throwable: false
289
- };
290
- }
291
- if (this.debug)
292
- (0, LogService_1.logInfo)("Commit transaction:", trx.id);
293
- this.transactions = this.transactions.filter(i => i.id !== tid);
294
- if (this.debug)
295
- (0, LogService_1.logInfo)("Transaction pool:", this.transactions);
296
- const err = await this.commit(trx);
297
- return err;
298
- };
299
- }
300
- async commit(trx) {
301
- try {
302
- await trx.conn.commit();
303
- trx.conn.removeAllListeners();
304
- trx.conn.release();
305
- }
306
- catch (e) {
307
- await this.rollbackTransaction(trx);
308
- return this.createMysqlQueryError(e);
309
- }
310
- return null;
311
- }
312
- async rollbackTransaction(trx, donNotRemove) {
313
- let err = null;
314
- try {
315
- (0, LogService_1.logInfo)("Rollback started", trx.conn.threadId);
316
- await trx.conn.rollback();
317
- await trx.conn.commit();
318
- trx.conn.removeAllListeners();
319
- trx.conn.release();
320
- if (!donNotRemove)
321
- this.transactions = this.transactions.filter(i => i.id !== trx.id);
322
- if (this.debug)
323
- (0, LogService_1.logInfo)("Rollback complete", trx.conn.threadId);
324
- }
325
- catch (e) {
326
- (0, LogService_1.logCrit)("${MysqlService.js}", "Can't rollback transaction", trx.queries);
327
- err = this.createMysqlQueryError(e);
328
- }
329
- this.storeTransactionAsProblem(trx, "rollback");
330
- return err;
331
- }
332
- async finishApp() {
333
- (0, LogService_1.logInfo)("Finishing mysql service");
334
- for (let i of this.transactions)
335
- this.rollbackTransaction(i);
336
- if (this.pool) {
337
- try {
338
- await this.pool.end();
339
- }
340
- catch (e) {
341
- (0, LogService_1.logCrit)("${MysqlService.js}", "Can't close MYSQL pool!");
342
- }
343
- }
344
- if (this.failReportFileStream)
345
- this.failReportFileStream.end();
346
- this.failReportFileStream = null;
347
- }
348
- prepareCountQuery(query) {
349
- let countQuery = query;
350
- if (countQuery.indexOf("LIMIT") === -1)
351
- countQuery = countQuery.substring(0, countQuery.indexOf("LIMIT"));
352
- if (countQuery.indexOf("ORDER") !== -1)
353
- countQuery = countQuery.substring(0, countQuery.indexOf("ORDER"));
354
- countQuery = countQuery.substring(countQuery.indexOf("FROM"));
355
- countQuery = "SELECT COUNT(1) as `count` " + countQuery;
356
- return countQuery;
357
- }
358
- async storeTransactionAsProblem(trx, message) {
359
- if (!this.options.transactionFailReport && !this.options.transactionFailReportDir) {
360
- (0, LogService_1.logCrit)("${MysqlService.js}", "Can't report failed transaction, no report function: transactionFailReport in options, and transactionFailReportDir isnt set");
361
- return;
362
- }
363
- if (this.options.transactionFailReportDir) {
364
- const yyymmdd = new Date().toISOString().substring(0, 10).replaceAll("-", "");
365
- const date = new Date();
366
- const file = path_1.default.resolve(this.options.transactionFailReportDir, yyymmdd + ".json");
367
- if (this.failReportFileStream) {
368
- if (this.failReportFileStreamName !== file) {
369
- this.failReportFileStream.end();
370
- this.failReportFileStream = null;
371
- }
372
- }
373
- if (this.failReportFileStreamName) {
374
- this.failReportFileStream = fs_1.default.createWriteStream(file, { flags: 'a' });
375
- this.failReportFileStreamName = file;
376
- }
377
- if (this.debug)
378
- (0, LogService_1.logInfo)("Store transaction fail report: ", file, trx.queries, message);
379
- if (!this.failReportFileStream)
380
- this.failReportFileStream = fs_1.default.createWriteStream(file, { flags: 'a' });
381
- this.failReportFileStream.write(JSON.stringify({ queries: trx.queries, time: trx.timestamp, date, message }) + "\n}EOB{\n", err => {
382
- if (err)
383
- (0, LogService_1.logCrit)("${MysqlService.js}", "Can't write to transaction fail report file");
384
- else
385
- (0, LogService_1.logInfo)("${MysqlService.js}", "Transaction fail report stored");
386
- });
387
- this.failReportLastAccessTime = Date.now();
388
- }
389
- if (this.options.transactionFailReport)
390
- this.options.transactionFailReport(trx, message);
391
- }
392
- async recreatePool() {
393
- (0, LogService_1.logInfo)("${MysqlService.js}", "Connecting to mysql: \n HOST: " + this.options.host + '\n PORT:' + this.options.port);
394
- if (this.pool) {
395
- this.pool.removeAllListeners();
396
- try {
397
- await this.pool.end();
398
- }
399
- catch (e) {
400
- (0, LogService_1.logCrit)("${MysqlService.js}", "Can't close MYSQL pool!");
401
- }
402
- this.pool = null;
403
- }
404
- try {
405
- this.pool = mysql.createPool({
406
- host: this.options.host,
407
- user: this.options.user,
408
- password: this.options.password,
409
- database: this.options.database,
410
- port: this.options.port,
411
- connectionLimit: this.options.connectionLimit,
412
- queueLimit: 10,
413
- multipleStatements: true,
414
- enableKeepAlive: true,
415
- keepAliveInitialDelay: 3 * 1000,
416
- idleTimeout: 1000 * 60 * 5
417
- });
418
- }
419
- catch (e) {
420
- (0, LogService_1.logCrit)("${MysqlService.js}", "Can't connect to MYSQL!");
421
- return false;
422
- }
423
- this.pool?.on('connection', (connection) => {
424
- if (this.debug)
425
- (0, LogService_1.logInfo)("${MysqlService.js}", "MYSQL CONNECTION CREATED");
426
- });
427
- this.pool?.on('acquire', (connection) => {
428
- if (this.debug)
429
- (0, LogService_1.logInfo)("${MysqlService.js}", "MYSQL CONNECTION ACQUIRED");
430
- });
431
- this.pool?.on('release', (connection) => {
432
- if (this.debug)
433
- (0, LogService_1.logInfo)("${MysqlService.js}", "MYSQL CONNECTION RELEASED");
434
- });
435
- this.pool?.on('enqueue', () => {
436
- if (this.debug)
437
- (0, LogService_1.logInfo)("${MysqlService.js}", "MYSQL CONNECTION ENQUEUED");
438
- });
439
- if (this.debug)
440
- (0, LogService_1.logInfo)("Check mysql connection");
441
- return new Promise(async (resolve, reject) => {
442
- try {
443
- const conn = await this.pool?.getConnection();
444
- if (conn) {
445
- const [res, f] = await conn.query("SELECT 1");
446
- conn?.release();
447
- (0, LogService_1.logInfo)("${MysqlService.js}", "Connected to MYSQL!");
448
- resolve(true);
449
- }
450
- else
451
- resolve(false);
452
- }
453
- catch (e) {
454
- (0, LogService_1.logCrit)("${MysqlService.js}", "Can't connect to MYSQL! " + e);
455
- resolve(false);
456
- }
457
- });
458
- }
459
- async onApplicationReady() { }
460
- static fieldsToObject(fields, ignoreSystemParameters) {
461
- if (!Array.isArray(fields))
462
- return fields;
463
- const obj = {};
464
- for (let i of fields) {
465
- if (!i.name)
466
- continue;
467
- if (typeof i.value !== "object")
468
- obj[i.name] = i.value;
469
- else {
470
- if (!ignoreSystemParameters) {
471
- obj[i.name] = {
472
- value: i.value,
473
- system: i.system,
474
- ignoreInInsert: i.ignoreInInsert,
475
- ignoreInUpdate: i.ignoreInUpdate,
476
- useInReplace: i.useInReplace,
477
- name: i.name
478
- };
479
- }
480
- else
481
- obj[i.name] = i.value;
482
- }
483
- }
484
- return obj;
485
- }
486
- static objectToFields(obj) {
487
- if (Array.isArray(obj))
488
- return obj;
489
- const fields = [];
490
- for (let i in obj) {
491
- if (obj[i] && typeof obj[i] === "object") {
492
- let mo = obj[i];
493
- if (!mo) {
494
- mo = {
495
- name: i,
496
- value: null,
497
- system: false,
498
- ignoreInInsert: false,
499
- ignoreInUpdate: false,
500
- useInReplace: false
501
- };
502
- }
503
- fields.push({
504
- name: mo.name ?? i,
505
- value: mo.value,
506
- system: mo.system,
507
- ignoreInInsert: mo.ignoreInInsert,
508
- ignoreInUpdate: mo.ignoreInUpdate,
509
- useInReplace: mo.useInReplace
510
- });
511
- }
512
- else {
513
- fields.push({
514
- name: i,
515
- value: obj[i]
516
- });
517
- }
518
- }
519
- return fields;
520
- }
521
- static prepareQuery(query, fields) {
522
- if (!Array.isArray(fields))
523
- fields = MysqlService.objectToFields(fields);
524
- for (let i of fields) {
525
- const val = this.prepareQueryFieldValue(i.value, i.system);
526
- i._parsedValue = val;
527
- query = query.replaceAll("@" + i.name, val + "");
528
- }
529
- const tmp = query.toLowerCase();
530
- if (tmp.indexOf("select") === 0 && tmp.indexOf("limit") === -1)
531
- query += " LIMIT 100";
532
- query = query.replaceAll("@NOLIMIT", "");
533
- if (query.indexOf("@fields") !== -1) {
534
- let insertFieldNames = [];
535
- let insertFieldValues = [];
536
- for (let i of fields) {
537
- if (i.ignoreInInsert)
538
- continue;
539
- insertFieldNames.push('`' + i.name.replaceAll("`", '').replaceAll('\"', "").replaceAll('\'', "") + '`');
540
- insertFieldValues.push(i._parsedValue);
541
- }
542
- query = query
543
- .replaceAll('@fields', insertFieldNames.join(","))
544
- .replaceAll('@values', insertFieldValues.join(","));
545
- }
546
- if (query.indexOf("@insert") !== -1) {
547
- let oninsertNames = [];
548
- let oninsertValues = [];
549
- for (let i of fields) {
550
- if (i.ignoreInInsert)
551
- continue;
552
- oninsertNames.push(i.name);
553
- oninsertValues.push(i._parsedValue);
554
- }
555
- query = query.replaceAll("@insert", `(${oninsertNames.join(",")}) VALUES (${oninsertValues.join(",")})`);
556
- }
557
- if (query.indexOf("@onupdate") !== -1) {
558
- let onUpdate = [];
559
- for (let i of fields) {
560
- if (i.ignoreInUpdate)
561
- continue;
562
- onUpdate.push('`' + i.name.replaceAll("`", '').replaceAll('\"', "").replaceAll('\'', "") + '` = ' + i._parsedValue);
563
- }
564
- query = query.replaceAll("@onupdate", onUpdate.join(" , "));
565
- }
566
- if (query.indexOf('@onduplicate') !== -1) {
567
- let onDuplicate = [];
568
- for (let i of fields) {
569
- if (!i.useInReplace)
570
- continue;
571
- onDuplicate.push('`' + i.name.replaceAll("`", '').replaceAll('\"', "").replaceAll('\'', "") + '` = ' + i._parsedValue);
572
- }
573
- query = query.replaceAll("@onduplicate", onDuplicate.join(" , "));
574
- }
575
- return query;
576
- }
577
- static prepareQueryFieldValue(value, system) {
578
- if (!system && typeof value === "string") {
579
- value = value ? value.replaceAll('"', '\\"') : null;
580
- if (value !== null)
581
- value = '"' + value + '"';
582
- else
583
- value = "NULL";
584
- }
585
- if (value === null || value === undefined)
586
- return "NULL";
587
- return value;
588
- }
589
- async execute(query, rollbackQuery, transactionID, throwable, calculateCount) {
590
- return new Promise(async (resolve, reject) => {
591
- if (!this.pool) {
592
- (0, LogService_1.logError)("${MysqlService.js}", "No pool");
593
- resolve({
594
- error: {
595
- code: "NO_POOL",
596
- errno: 100000,
597
- fatal: true,
598
- sql: query,
599
- name: "NO_POOL",
600
- message: "Mysql pool not created",
601
- throwable: throwable ? true : false
602
- },
603
- data: null,
604
- count: 0
605
- });
606
- return;
607
- }
608
- try {
609
- let conn = null;
610
- if (transactionID && transactionID > 0) {
611
- conn = this.transactions.find(i => i.id === transactionID)?.conn ?? null;
612
- if (this.debug)
613
- (0, LogService_1.logInfo)("Execute query on transaction: ", conn?.threadId);
614
- }
615
- else {
616
- conn = await this.pool.getConnection();
617
- }
618
- if (this.debug)
619
- (0, LogService_1.logInfo)("Execute query", conn?.threadId);
620
- if (!conn) {
621
- (0, LogService_1.logCrit)("${MysqlService.js}", `No connection created!`);
622
- resolve({
623
- error: {
624
- code: "NO_CONN",
625
- errno: 100001,
626
- fatal: true,
627
- sql: query,
628
- name: "NO_CONN",
629
- message: "Mysql pool cant get connection",
630
- throwable: throwable ? true : false
631
- },
632
- data: null,
633
- count: 0
634
- });
635
- return;
636
- }
637
- for (let i of this.transactions) {
638
- if (i.conn === conn) {
639
- (0, LogService_1.logInfo)("Your connection is in transaction");
640
- break;
641
- }
642
- }
643
- this.sendQuery(conn, query, resolve, rollbackQuery, throwable ? true : false, calculateCount);
644
- }
645
- catch (e) {
646
- (0, LogService_1.logError)("${MysqlService.js}", e);
647
- if (`${e}`.indexOf('ECONNREFUSED') !== -1)
648
- this.recreatePool();
649
- resolve({
650
- error: {
651
- code: "NO_CONN",
652
- errno: 100001,
653
- fatal: true,
654
- throwable: throwable ? true : false,
655
- sql: query,
656
- name: "NO_CONN",
657
- message: (e && typeof e === "object" && "message" in e) ? e.message : "Mysql cant get connection"
658
- },
659
- data: null,
660
- count: 0
661
- });
662
- return;
663
- }
664
- });
665
- }
666
- async sendQuery(conn, query, resolve, rollback, throwable, calculateCount) {
667
- conn.on("error", async (err) => {
668
- let rollbackError = null;
669
- if (rollback)
670
- rollbackError = (await this.queryAsync(conn, rollback)).err;
671
- (0, LogService_1.logError)("${MysqlService.js}->conn.on('error')", err);
672
- try {
673
- conn.removeAllListeners();
674
- conn.destroy();
675
- }
676
- catch (e) { }
677
- resolve({
678
- error: {
679
- code: "CONN_ERR",
680
- errno: 100003,
681
- fatal: true,
682
- sql: query,
683
- name: "CONN_ERR",
684
- message: "Error: " + err,
685
- throwable: throwable
686
- },
687
- data: null,
688
- rollbackError: rollbackError,
689
- count: 0
690
- });
691
- });
692
- (0, LogService_1.logInfo)("${MysqlService.js}", query);
693
- const queryResult = await this.queryAsync(conn, query);
694
- if (queryResult.err) {
695
- let rollbackError = null;
696
- if (rollback)
697
- rollbackError = (await this.queryAsync(conn, rollback)).err;
698
- try {
699
- let doclose = false;
700
- if (queryResult.err && queryResult.err.message) {
701
- if (queryResult.err.message.toLowerCase().indexOf("can't add new command when connection is in closed state") !== -1) {
702
- doclose = true;
703
- }
704
- }
705
- if (doclose) {
706
- conn.destroy();
707
- conn.removeAllListeners();
708
- queryResult.err.code = "CONN_ERR";
709
- }
710
- else {
711
- conn.release();
712
- conn.removeAllListeners();
713
- }
714
- }
715
- catch (e) { }
716
- let dup = false;
717
- if (queryResult.err && queryResult.err.code && queryResult.err.code.toLowerCase().indexOf("er_dup_entry") !== -1)
718
- dup = true;
719
- (0, LogService_1.logError)("${MysqlService.js}->send query->query error", queryResult.err);
720
- resolve({
721
- error: { ...queryResult.err, throwable: throwable },
722
- data: null,
723
- rollbackError: rollbackError,
724
- isDuplicateError: dup,
725
- count: 0
726
- });
727
- return;
728
- }
729
- let count = 0;
730
- if (calculateCount && query.indexOf("SELECT") === 0) {
731
- let countQuery = this.prepareCountQuery(query);
732
- const countQueryResult = await this.queryAsync(conn, countQuery);
733
- if (countQueryResult.err)
734
- (0, LogService_1.logError)("${MysqlService.js}->send query->count->query error", countQueryResult.err);
735
- else {
736
- if (countQueryResult.results && countQueryResult.results.length > 0) {
737
- count = countQueryResult.results[0].count;
738
- }
739
- }
740
- }
741
- try {
742
- conn.release();
743
- conn.removeAllListeners();
744
- }
745
- catch (e) { }
746
- const err = null;
747
- resolve({
748
- error: err,
749
- data: queryResult.results,
750
- count: count
751
- });
752
- }
753
- async queryAsync(conn, query) {
754
- let result = null;
755
- try {
756
- result = await conn.query(query);
757
- }
758
- catch (e) {
759
- return { err: this.createMysqlQueryError(e) };
760
- }
761
- return {
762
- err: null,
763
- results: result[0],
764
- };
765
- }
766
- createMysqlQueryError(err, throwable) {
767
- if (err && typeof err === "object" && "code" in err && "errno" in err && "sql" in err && "name" in err && "message" in err) {
768
- return {
769
- code: err.code,
770
- errno: err.errno,
771
- sql: err.sql,
772
- name: err.name,
773
- message: err.message,
774
- throwable: throwable ? true : false
775
- };
776
- }
777
- else {
778
- return {
779
- code: "QUERY_ERR",
780
- errno: 100002,
781
- fatal: true,
782
- sql: "no query",
783
- name: "QUERY_ERR",
784
- message: "Error: " + (err) ? err : "",
785
- throwable: throwable ? true : false
786
- };
787
- }
788
- }
789
- }
790
- exports.MysqlService = MysqlService;
791
- const secret_key = "AKLWkajw%^&dgwqhw#98453i23bfk23rn2knknglrgjeit";
792
- const secret_iv = "rthadrfk23rn2kn#*FNKA@gt44df3tslrgj##!it";
793
- const key = (0, crypto_1.createHash)('sha512').update(secret_key).digest('hex').substring(0, 32);
794
- const iv = (0, crypto_1.createHash)('sha512').update(secret_iv).digest('hex').substring(0, 16);
795
- const decrypt = (encrypted) => {
796
- try {
797
- encrypted = Buffer.from(encrypted, 'base64').toString('binary');
798
- const decipher = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, iv);
799
- let decrypted = decipher.update(encrypted, 'binary', 'utf8');
800
- decrypted += decipher.final('utf8');
801
- return decrypted;
802
- }
803
- catch (e) {
804
- return null;
805
- }
806
- };
807
- const encrypt = (txt) => {
808
- try {
809
- let encipher = (0, crypto_1.createCipheriv)('aes-256-cbc', key, iv), encrypted = encipher.update(txt, 'utf8', 'binary');
810
- encrypted += encipher.final('binary');
811
- return Buffer.from(encrypted, 'binary').toString('base64');
812
- }
813
- catch (e) {
814
- return null;
815
- }
816
- };
817
- exports.default = MysqlService;