Skip to content

Commit

Permalink
2.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
aaferna committed Jun 25, 2023
1 parent 3eb17e9 commit 4b3eb0f
Show file tree
Hide file tree
Showing 15 changed files with 146 additions and 307 deletions.
Binary file added .DS_Store
Binary file not shown.
6 changes: 3 additions & 3 deletions .env
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
PORT=1800
PORT=1900
DDOSSTATUS=0
DDOSINTENTOS=3
DDOSTIMOUT=600000
DDOSINTENTOS=10
DDOSTIMOUT=10000 # 86400000 es un dia
Binary file added db/.DS_Store
Binary file not shown.
7 changes: 5 additions & 2 deletions db/datastores.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
{
"datastore":[
{
"name": "manager",
"name": "test",
"conn":{
"server": "localhost",
"user": "root",
"password": "",
"port": 3306,
"connectionreintent": 5,
"database": ""
"database": "test",
"connectionLimit": 10,
"waitForConnections": 10,
"queueLimit": 10
}
}
]
Expand Down
Binary file added db/endpoint_stats.db
Binary file not shown.
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ require("dotenv").config();

global.datetoDay = require("./modules/date").datetoDay
global.dateNow = require("./modules/date").dateNow
global.dateDB = require("./modules/date").dateDB
global.datetoJSON = require("./modules/date").datetoJSON
global.log = require("./modules/log4j").log
global.port = parseInt(process.env.PORT) || 3000;
Expand Down
8 changes: 7 additions & 1 deletion modules/date.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ const formatearFecha = (fecha) => {
return fecha.setZone('America/Argentina/Buenos_Aires');
};

const dateDB = () => {
let date = formatearFecha(DateTime.local());
return date.toFormat('yyyy-MM-dd HH:mm:ss');
};

const dateNow = () => {
let date = formatearFecha(DateTime.local());
return date.toLocaleString(DateTime.DATETIME_FULL);
Expand All @@ -29,5 +34,6 @@ const datetoJSON = () => {
module.exports = {
datetoDay,
dateNow,
datetoJSON
datetoJSON,
dateDB
};
5 changes: 1 addition & 4 deletions modules/expressHandle.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const blockedIPs = [];
exports.reqInfo = (req) =>{
return {
id: randomUUID(),
ip: req.headers['x-forwarded-for'] || req.socket.remoteAddress,
ip: req.headers['x-forwarded-for'],
uri: req.originalUrl,
method: req.method
}
Expand Down Expand Up @@ -82,9 +82,6 @@ exports.DDOSBlock = (req, res, next) => {
next();
}




setInterval(() => {
const currentTime = new Date();
blockedIPs.forEach((ip, index) => {
Expand Down
123 changes: 69 additions & 54 deletions modules/sql.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,93 @@
const mysql = require("mysql2");
const mysqlSy = require('sync-mysql')
const dbconect = require("../db/datastores.json").datastore
const mysql = require('mysql2/promise');

function executeSQL(database, sql) {
let dataconnection;
const selectedDB = dbconect.find(item => item.name === database);
async function executeSQLS(database, sql) {
try {
const selectedDB = dbconect.find(item => item.name === database);

if (!selectedDB) {
log("error", `El Conector "${database}" no es correcto o no existe`, "SQL");
return { status: 0 };
}

if (selectedDB) {
dataconnection = mysql.createConnection({
const pool = mysql.createPool({
connectionLimit: selectedDB.conn.connectionLimit,
host: selectedDB.conn.server,
user: selectedDB.conn.user,
password: selectedDB.conn.password,
connectTimeout: selectedDB.conn.connectTimeout,
database: selectedDB.conn.database,
multipleStatements: true
waitForConnections: true,
queueLimit: 0
});
} else {
log("error", `El Conector "${database}" no es correcto o no existe`, "SQL");
return Promise.resolve({ status: 0 });
}

return new Promise((resolve, reject) => {
try {
dataconnection.query(sql, (error, results) => {
if (error) {
log("error", `Existe un error en la consulta :: ${error}`, "SQL");
resolve({ status: 0 });
}
resolve(results);
});
} catch (error) {
log("error", `Existe un error en la consulta :: ${error}`, "SQL");
resolve({ status: 0 });
}
});
}

function executeSQLS (database, sql) {
try{

let connection;
let response;

const selectedDB = dbconect.find(item => item.name === database);
const [rows, fields] = await pool.execute(sql);

if (selectedDB) {
await pool.end();

connection = new mysqlSy({
host: selectedDB.conn.server,
user: selectedDB.conn.user,
password: selectedDB.conn.password,
connectTimeout: selectedDB.conn.connectTimeout,
database: selectedDB.conn.database
});
return rows;
} catch (error) {
log("error", `Existe un error en la consulta :: ${error}`, "SQL");

if (error.code === 'PROTOCOL_CONNECTION_LOST') {
// Si la conexión se pierde, se vuelve a intentar una vez
log("warning", `Se perdió la conexión con la base de datos. Reintentando la consulta...`, "SQL");
return executeSQLS(database, sql);
} else if (error.code === 'POOL_ENQUEUELIMIT') {
// Si se alcanza el límite de la pool, se muestra una advertencia y se espera antes de reintentar
log("warning", `Se alcanzó el límite de conexiones permitido. Esperando antes de reintentar...`, "SQL");
await new Promise(resolve => setTimeout(resolve, 5000));
return executeSQLS(database, sql);
} else {
// Cualquier otro error se maneja como una falla
return { status: 0 };
}
}
}

async function executeSQL(database, sql, values) {
try {
const selectedDB = dbconect.find(item => item.name === database);

if (!selectedDB) {
log("error", `El Conector "${database}" no es correcto o no existe`, "SQL");
return { status: 0 };

}

response = connection.query(sql)
connection.finishAll()
const pool = mysql.createPool({
connectionLimit: selectedDB.conn.connectionLimit,
host: selectedDB.conn.server,
user: selectedDB.conn.user,
password: selectedDB.conn.password,
database: selectedDB.conn.database,
waitForConnections: true,
queueLimit: 0
});

const [rows, fields] = await pool.execute(sql, values);

return response;
await pool.end();

return rows;
} catch (error) {
log("error", `Existe un error en la consulta :: ${error}`, "SQL")
return { status: 0 };
log("error", `Existe un error en la consulta :: ${error}`, "SQL");

if (error.code === 'PROTOCOL_CONNECTION_LOST') {
// Si la conexión se pierde, se vuelve a intentar una vez
log("warning", `Se perdió la conexión con la base de datos. Reintentando la consulta...`, "SQL");
return executeSQLS(database, sql, values);
} else if (error.code === 'POOL_ENQUEUELIMIT') {
// Si se alcanza el límite de la pool, se muestra una advertencia y se espera antes de reintentar
log("warning", `Se alcanzó el límite de conexiones permitido. Esperando antes de reintentar...`, "SQL");
await new Promise(resolve => setTimeout(resolve, 5000));
return executeSQLS(database, sql, values);
} else {
// Cualquier otro error se maneja como una falla
return { status: 0 };
}
}
}

module.exports = {
executeSQL,
executeSQLS
};

exports.executeSQLS = executeSQLS;

exports.executeSQL = executeSQL
Loading

0 comments on commit 4b3eb0f

Please sign in to comment.