3

In my project, I am using MySQL database. The problem is, that I don't know how to write simple database module to one js file.

My code is:

File: database.js

var mysql = require("mysql");

var connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mydb"
});

module.exports = class Database {

    constructor() {
        connection.connect(function (err) {
            if (err) {
                console.error(err);
                throw err;
            } else {
                console.log("Connection to database was successful");
            }
        });
    }

    getConnection() { return connection; }
};

I have a lot of files in project and each one needs use database, the problem is, when I import database.js constructor is every time called, I think, its a bad way.

Is there any better way how to use database connection in project? Somethink like call getConnection() from database.js file without call constructor.

Thank you for any help.

2
  • Consider using a Singleton for your database. You can also return an instance of a Database inside the module : module.exports = new Database(); Commented Sep 9, 2017 at 15:34
  • Simply move the stuff inside the constructor outside of the class definition? Commented Sep 9, 2017 at 16:33

2 Answers 2

3

A possible solution:

const mysql = require("mysql"),
      connection = mysql.createConnection({
          host: "localhost",
          user: "root",
          password: "",
          database: "mydb"
      });

connection.connect(function (err) {
    if (err) {
      console.error(err);
      throw err;
   } else {
    console.log("Connection to database was successful");
  }
});

module.exports =  {
  getConnection() { return connection; }
};
Sign up to request clarification or add additional context in comments.

Comments

1

In your database.js file while exporting write:

modules.exports = new Database();

And use

require('./path/to/database-file')

Wherever you have to use the instance, It will always get the same object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.