node-red-contrib-services-mentor
Version:
Mentor Services
99 lines (90 loc) • 3.47 kB
JavaScript
module.exports = function(RED) {
var mysql = require('mysql');
var reconnect = RED.settings.mysqlReconnectTime || 20000;
var log = RED.log;
function MySQLNode(n) {
RED.nodes.createNode(this,n);
this.host = n.host;
this.port = n.port;
this.tz = n.tz || "local";
this.connected = false;
this.connecting = false;
this.dbname = n.db;
this.setMaxListeners(0);
var node = this;
function checkVer() {
node.connection.query("SELECT version();", [], function(err, rows) {
if (err) {
node.connection.release();
node.error(err);
node.status({fill:"red",shape:"ring",text:"Bad Ping"});
doConnect();
}
});
}
function doConnect() {
node.connecting = true;
node.emit("state","connecting");
if (!node.pool) {
node.pool = mysql.createPool({
host : node.host,
port : node.port,
user : node.credentials.user,
password : node.credentials.password,
database : node.dbname,
timezone : node.tz,
insecureAuth: true,
multipleStatements: true,
connectionLimit: 25
});
}
node.pool.getConnection(function(err, connection) {
node.connecting = false;
if (err) {
node.emit("state",err.code);
node.error(err);
node.tick = setTimeout(doConnect, reconnect);
}
else {
node.connection = connection;
node.connected = true;
node.emit("state","connected");
node.connection.on('error', function(err) {
node.connected = false;
node.connection.release();
node.emit("state",err.code);
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
doConnect(); // silently reconnect...
}
else if (err.code === 'ECONNRESET') {
doConnect(); // silently reconnect...
}
else {
node.error(err);
doConnect();
}
});
if (!node.check) { node.check = setInterval(checkVer, 290000); }
}
});
}
this.connect = function() {
if (!this.connected && !this.connecting) {
doConnect();
}
}
this.on('close', function (done) {
if (this.tick) { clearTimeout(this.tick); }
if (this.check) { clearInterval(this.check); }
node.connected = false;
node.emit("state"," ");
node.pool.end(function (err) { done(); });
});
}
RED.nodes.registerType("MySQLdb",MySQLNode, {
credentials: {
user: {type: "text"},
password: {type: "password"}
}
});
}