I have database.js file that connects to db and manage connections I export connection and reuse it in my app
var mysql = require('mysql');
pool = mysql.createPool({
host: cfg.mysql.host,
user: cfg.mysql.user,
password: cfg.mysql.pass,
database: cfg.mysql.db,
port: cfg.mysql.port
});
function handleDisconnect() {
pool.getConnection(function(err, cnt) {
module.exports.connection = cnt;
});
pool.on('error', function (err) {
console.log(err);
});
};
handleDisconnect();
process.on('uncaughtException', function (err) {
console.error(err.code);
if(err.code === "PROTOCOL_CONNECTION_LOST")
handleDisconnect();
console.log("Node NOT Exiting...");
});
app.js
var db = require('./database');
app.get('/test', function(req, res) {
db.connection.query('SELECT * from table', function(err, result) {
console.log(result);
});
}
This works fine. My problem is when the mysql server disconnect. I handle this error by recalling the handleDisconnect() function to get a new connection. However, when that happens the connection is undefined in my app.js when I navigate to my browser /test
TypeError: Cannot call method 'query' of undefined
Thoughts?