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.
Databaseinside the module :module.exports = new Database();