Reputation: 320
I have my mysql connection in database.js
along with a disconnect handler to restart connection when it disconnects. which looks like this:
const mysql = require('mysql');
function handleDisconnect() {
con = mysql.createConnection({
host: "host",
user: "user",
password: "pass",
database: "db",
debug: false
});
con.connect(function(err) {
if(err) {
setTimeout(handleDisconnect, 2000, con);
}
});
con.on('error', function(err) {
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
} else {
throw err;
}
});
}
handleDisconnect();
module.exports = {
con,
}
I want to use this same connection across multiple files. For example in test.js
:
var con = require('database.js').con;
con.query(sql, function (err, result) {
if (err) {
console.log("ERROR");
}
});
However this creates a local copy of the connection and when the connection disconnects, the handleDisconnect
function does not restart this connection.
What is the best way to fix this?
Upvotes: 0
Views: 54
Reputation: 707326
Objects are shared by pointer so as long as you always refer to the .con
property via the object and as long as whoever manipulates the con
property also changes the one in the exported object, it should work. So, change your importing code to this:
var dbInfo = require('database.js');
dbInfo.con.query(sql, function (err, result) {
if (err) {
console.log("ERROR");
}
});
Then, anytime the con
property is updated, as long as you refer to it via the dbInfo
object (and don't make your own local copy), you will see the latest value of the exported property.
When you do it this way, dbInfo
points at the exact same object that you exported in your source module. So, if your source module changes or updates the .conn
property on that object, any other modules you share it with will also see that updated property.
Note, you will have to change the code in the exporting module so that it keeps the exported object up-to-date with the latest value of con
too. You will need to save a copy of the object you exported (or refer to it from module.exports
) and make sure that module.exports.con
always has the latest value you want everyone to use. Do, not assign a new object to module.exports
. Just update the .con
property on the object that's already there because that's the object that was already exported.
function handleDisconnect() {
con = module.exports.con = mysql.createConnection({
host: "host",
user: "user",
password: "pass",
database: "db",
debug: false
});
If you needed to know dynamically exactly when the connection changed, you could export an EventEmitter
object and emit an event on that emitter any time the conn
value changed so any people using this could listen for that event and dynamically know when the value was updated.
Upvotes: 1