-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdb.js
37 lines (33 loc) · 974 Bytes
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'use strict';
let mysql = require('mysql');
let conn = mysql.createConnection(require('./config').mysql);
/**
* MySQL will close the connection if there is no activity for some time.
* See: http://stackoverflow.com/questions/20210522/nodejs-mysql-error-connection-lost-the-server-closed-the-connection
*/
let disconnectHandler = function() {
conn.on('error', (err) => {
if (!err.fatal) {
return;
}
if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
throw err;
}
conn.destroy();
conn = mysql.createConnection(require('./config').mysql);
disconnectHandler();
});
};
disconnectHandler();
module.exports = {
getConn: function() {
return conn;
},
recreateConn: function () {
try {
conn.destroy();
} catch(e) { /* nothing to do here */ }
conn = mysql.createConnection(require('./config').mysql);
disconnectHandler();
}
};