projeto-hit/TEST_SERVER1/whats/helpers/mysql_conn.js

130 lines
3.1 KiB
JavaScript
Raw Normal View History

const dotenv = require('dotenv');
dotenv.config({ path: `${process.cwd()}/.env` });
const path = require('path')
// Ubicua Plataform - MYSQL Module
try{
var mysql_npm = require('mysql');
}catch(err){
console.log("Cannot find `mysql` module. Is it installed ? Try `npm install mysql` or `npm install`.");
}
var db_config = {
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PASS,
database : process.env.DB,
charset : 'utf8mb4_general_ci',
port : process.env.DB_PORT
};
//-
//- Connection configuration
//-
// var db_config = {
// host : 'localhost',
// user : 'whaticket',
// password : '9147teste',
// database : 'db_cdnwork',
// charset : 'utf8mb4_general_ci',
// port : '6603'
// };
// var db_config = {
// host : '172.31.187.7',
// user : 'todoo',
// password : '7901228899',
// database : 'db_cdnwork',
// charset : 'utf8mb4_general_ci'
// };
//-
//- Create the connection variable
//-
var connection = mysql_npm.createPool(db_config);
//-
//- Establish a new connection
//-
connection.getConnection(function(err){
if(err) {
// mysqlErrorHandling(connection, err);
console.log("\n\t *** Cannot establish a connection with the database. ***");
connection = reconnect(connection);
}else {
console.log("\n\t *** New connection established with the database. ***")
}
});
//-
//- Reconnection function
//-
function reconnect(connection){
console.log("\n New connection tentative...");
//- Create a new one
connection = mysql_npm.createPool(db_config);
//- Try to reconnect
connection.getConnection(function(err){
if(err) {
//- Try to connect every 2 seconds.
setTimeout(reconnect(connection), 2000);
}else {
console.log("\n\t *** New connection established with the database. ***")
return connection;
}
});
}
//-
//- Error listener
//-
connection.on('error', function(err) {
//-
//- The server close the connection.
//-
if(err.code === "PROTOCOL_CONNECTION_LOST"){
console.log("/!\\ Cannot establish a connection with the database. /!\\ ("+err.code+")");
return reconnect(connection);
}
else if(err.code === "PROTOCOL_ENQUEUE_AFTER_QUIT"){
console.log("/!\\ Cannot establish a connection with the database. /!\\ ("+err.code+")");
return reconnect(connection);
}
else if(err.code === "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR"){
console.log("/!\\ Cannot establish a connection with the database. /!\\ ("+err.code+")");
return reconnect(connection);
}
else if(err.code === "PROTOCOL_ENQUEUE_HANDSHAKE_TWICE"){
console.log("/!\\ Cannot establish a connection with the database. /!\\ ("+err.code+")");
}
else{
console.log("/!\\ Cannot establish a connection with the database. /!\\ ("+err.code+")");
return reconnect(connection);
}
});
//-
//- Export
//-
module.exports = connection;