dkanavis

Untitled

Jun 30th, 2015
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /****** Load database wrapper *******/
  2.     function loadDatabase(cb, reconn) {
  3.         global.db = require('mysql').createConnection({
  4.             host       : global.config.db_use_socket ? undefined : global.config.db_host,
  5.             port       : global.config.db_use_socket ? undefined : global.config.db_port,
  6.             socketPath : global.config.db_use_socket ? global.config.db_socket : undefined,
  7.             user       : global.config.db_user,
  8.             password   : global.config.db_password,
  9.             database   : global.config.db_db,
  10.         });
  11.         global.db.connect(function (err) {
  12.             if (err) {
  13.                 if (reconn) {
  14.                     e('error reconnecting to main database: ' + err.message+'. Retrying in 2 seconds...');
  15.                     setTimeout(loadDatabase.bind(null, function(){}, true), 2000);
  16.                 } else {
  17.                     crit('error connecting to main database: ' + err.message);
  18.                 }
  19.             } else {
  20.                 p('Connected to main database');
  21.                 /****** Make database method wrapper for squel *******/
  22.                 global.db.squery = function () { arguments[0] = arguments[0].toString(); this.query.apply(this, arguments); }
  23.                
  24.                 cb();
  25.             }
  26.         });
  27.         /****** Database reconnect *******/
  28.         global.db.on('error', function (err) {
  29.             if (err.code === 'PROTOCOL_CONNECTION_LOST') {
  30.                 e('Lost connection to main database. Reconnecting in 2 seconds...');
  31.                 setTimeout(loadDatabase.bind(null, function(){}, true), 2000);
  32.             } else {
  33.                 e('Main DB error: ' + err.message);
  34.             }
  35.         });
  36.     }
  37.    
  38.     loadDatabase(function () {
  39.         ....
Advertisement
Add Comment
Please, Sign In to add comment