I am newbie in nodejs and api development, I have written following code for creating connection to database and using them by calling connection.query.
Here is code for create Connection module and call them in my model class. I have to pass database dynamically as in my project there could be multiple databases.
It is creating multiple database connection. How can I change it to single database connection which should be used in whole app ,quickly without making much changes in code.
db.js:
var mysql = require('mysql');
module.exports = dbConnection = (dbname) => {
console.log('mysql inside dynamic db...');
return connection = mysql.createConnection({
host: process.env.DBHost || 'localhost',
port: process.env.DBPort || 3306,
user: process.env.DBUser || 'root',
password: process.env.DBPassword || '',
database: process.env.DBName || dbname
});
};
for query :
//get financial year
Employee.getYear = function getYear(req_decoded, result) {
var myPromise = dbname(req_decoded);
myPromise.then(function(myDBName) {
new_conn(myDBName).query("Select id,name from " + myDBName + ".financial_year", function(err, res) {
if (err) {
//console.log("error: ", err);
result(null, err);
} else {
result(null, JSON.stringify({
"statusCode": 200,
"status": "success",
"data": res
}));
}
});
});
};
I am getting the database name from another database and using promise to get the database name.
Any help would be appreciated.