Monday, 15 May 2017

Node.js Module class returns undefined

This is my database class which I want to exist only once because I want only one connection for the application and not multiple connections.

var mysql = require('mysql');
var fs = require("fs");
var eventEmitter = require("./events.js");

function Database() {
  this.connection;
  this.poolCluster;

  var host;
  var username;
  var password;
  var db;

  var config;
  var clusterConfig = {
    removeNodeErrorCount: 5,
    restoreNodeTimeout: 1000,
    defaultSelector: 'ORDER'
  };

  var poolConfig = {
    acquireTimeout: 10000,
    waitForConnections: false,
    connectionLimit: 10,
    queueLimit: 0
  };

  this.connect = function() {
    this.connection = mysql.createConnection({
      host: config.mysqlHost,
      user: config.mysqlUsername,
      password: config.mysqlPassword,
      database: config.mysqlDb
    });

    this.connection.connect(function(err) {
      if(err) {
        console.error("Connection couldn't established at " + config.mysqlHost + " (user: " + config.mysqlUsername + ")"
        + "\nError: " + err);
        return;
      }

      console.log("Connected to mysql server at " + config.mysqlHost + " (user: " + config.mysqlUsername + ")");

      this.poolCluster = mysql.createPoolCluster(clusterConfig);

      this.poolCluster.add("APP", poolConfig);
      this.poolCluster.add("ACCOUNTS", poolConfig);
      this.poolCluster.add("GAME", poolConfig);

      console.log("Created Connection Clusters\n- APP\n- ACCOUNTs \n- GAME");
      eventEmitter.emit("MysqlConnectionReady");
    });
  };

  this.getMainConnection = function() {
    return this.connection;
  };

  this.getAppConnection = function() {
    this.poolCluster.getConnection("APP", 'ORDER', function(err, connection) {
      if(err) throw err;

      return connection;
    });
  };

  this.getAccountsConnection = function() {
    this.poolCluster.getConnection("ACCOUNTS", 'ORDER', function(err, connection) {
      if(err) throw err;

      return connection;
    });
  };

  this.getGameConnection = function() {
    this.poolCluster.getConnection("GAME", 'ORDER', function(err, connection) {
      if(err) throw err;

      return connection;
    });
  };


    fs.readFile(process.cwd() + "/config.json", 'utf8', function(err, data) {
      if(err) throw err;

      config = JSON.parse(data);
      this.connect();
    });
}

module.exports = Database:

In my code I set module.exports = Database; When I want to use Database in another file its undefined. I want to use this in another file and I want to use only instance of that because I want only one connection for the app Im running.

But if I use require('./Database.js'j; and use the var it returns undefined



via Nightloewe

No comments:

Post a Comment