Advertisement
Guest User

Untitled

a guest
May 2nd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const mysql = require('mysql');
  2. const config = require('../config.js');
  3. const db_config = {
  4.     host: config.dbHost,
  5.     user: config.dbUsername,
  6.     password: config.dbPassWord,
  7.     database: config.dbName
  8. };
  9.  
  10. class Database {
  11.     constructor() {
  12.         this.connection;
  13.         this.handleDisconnect();
  14.     }
  15.  
  16.     query(sql, args) {
  17.         return new Promise((resolve, reject) => {
  18.             this.connection.query(sql, args, (err, rows) => {
  19.                 if (err)
  20.                     return reject(err);
  21.                 return resolve(rows);
  22.             });
  23.         });
  24.     }
  25.     close() {
  26.         return new Promise((resolve, reject) => {
  27.             this.connection.end(err => {
  28.                 if (err)
  29.                     return reject(err);
  30.                 resolve();
  31.             });
  32.         });
  33.     }
  34.  
  35.     handleDisconnect() {
  36.         this.connection = mysql.createConnection(db_config); // Recreate the connection, since
  37.         // the old one cannot be reused.
  38.  
  39.         this.connection.connect(function(err) { // The server is either down
  40.             if (err) { // or restarting (takes a while sometimes).
  41.                 console.log('error when connecting to db:', err);
  42.                 setTimeout(this.handleDisconnect(), 2000); // We introduce a delay before attempting to reconnect,
  43.             } // to avoid a hot loop, and to allow our node script to
  44.         }); // process asynchronous requests in the meantime.
  45.         // If you're also serving http, display a 503 error.
  46.        this.connection.on('error', function(err) {
  47.             console.log('db error', err);
  48.             if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
  49.                 this.handleDisconnect(); // lost due to either server restart, or a
  50.             } else { // connnection idle timeout (the wait_timeout
  51.                 throw err; // server variable configures this)
  52.             }
  53.         });
  54.     }
  55.  
  56. }
  57.  
  58.  
  59. module.exports = Database;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement