Good, I have a REST API made in NodeJS and ExpressJS and the problem I'm having is that after several hours without making any request, the connection to MYSQL is closed, then when making a request the connection is closed, I get that error and even though the API keeps running, no query to the DB that I want to do will work until I restart it. I saw something of handleDisconnect and pool but I have not managed anything to work, in addition to this I would also like that if intentionally or for anything the server of mysql is closed neither crashee the API by connect ECONNREFUSED 127.0.0.1:3306
. Simply try to connect silently until the MYSQL server is available again and connect. You could even log a message but not that the API crash.
Server.js
REST.prototype.connectMysql = function() {
var self = this;
var pool = mysql.createPool({
connectionLimit : 100,
waitForConnections : true,
host : process.env.RDS_HOSTNAME,
user : process.env.RDS_USERNAME,
password : process.env.RDS_PASSWORD,
database : process.env.RDS_DB_NAME,
debug : false,
wait_timeout : 28800,
connect_timeout :10
});
pool.getConnection(function(err,connection){
if(err) {
self.stop(err);
} else {
self.configureExpress(connection);
}
});
}
REST.prototype.configureExpress = function(connection) {
var self = this;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
app.use('/api', router);
var rest_router = new rest(router,connection,md5);
self.startServer();
}
REST.prototype.startServer = function() {
app.listen(3000,function(){
console.log("All right ! I am alive at Port 3000.");
});
}
REST.prototype.stop = function(err) {
console.log("ISSUE WITH MYSQL n" + err);
process.exit(1);
}
new REST();
A REST.js endpoint
router.get("/users/one/:id", function(req,res){
var query = "SELECT * FROM ?? WHERE ?? = ?";
var table = ["users", "id", req.params.id];
query = mysql.format(query, table);
connection.query(query,function(err,rows){
if(err) {
console.log(err)
res.json(err);
} else {
res.json(rows);
}
});
});