Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const mysql = require('mysql');
- const config = require('../config.js');
- const db_config = {
- host: config.dbHost,
- user: config.dbUsername,
- password: config.dbPassWord,
- database: config.dbName
- };
- class Database {
- constructor() {
- this.connection;
- this.handleDisconnect();
- }
- query(sql, args) {
- return new Promise((resolve, reject) => {
- this.connection.query(sql, args, (err, rows) => {
- if (err)
- return reject(err);
- return resolve(rows);
- });
- });
- }
- close() {
- return new Promise((resolve, reject) => {
- this.connection.end(err => {
- if (err)
- return reject(err);
- resolve();
- });
- });
- }
- handleDisconnect() {
- this.connection = mysql.createConnection(db_config); // Recreate the connection, since
- // the old one cannot be reused.
- this.connection.connect(function(err) { // The server is either down
- if (err) { // or restarting (takes a while sometimes).
- console.log('error when connecting to db:', err);
- setTimeout(this.handleDisconnect(), 2000); // We introduce a delay before attempting to reconnect,
- } // to avoid a hot loop, and to allow our node script to
- }); // process asynchronous requests in the meantime.
- // If you're also serving http, display a 503 error.
- this.connection.on('error', function(err) {
- console.log('db error', err);
- if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
- this.handleDisconnect(); // lost due to either server restart, or a
- } else { // connnection idle timeout (the wait_timeout
- throw err; // server variable configures this)
- }
- });
- }
- }
- module.exports = Database;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement