Reputation: 536
I use mysql (without sequelize) and generally create the connection in a module.export function which I then require from other files like so:
var db;
module.exports={
getConnection = function (){return new Promise(function(resolve, reject){
// db = mysql connection stuff
resolve(db)
});},
//other database related operations similarly
}
Now, I want to separate everything for example, I want to have a userModel that will have a few database operations related to users which will just import the db connection and so on; But what is the optimal way of achieving this? Thanks.
Upvotes: 0
Views: 107
Reputation: 1350
Since it's used so broadly and doesn't present a high risk of variable naming conflict, I prefer to add it to the global object. Then you never have to make sure it's being included, passed, or imported from a module.
Consider the following example:
// in your application initialization file such as app.js
// require items …
const mysql = require('mysql');
const connection = mysql.createPool({
connectionLimit: 10,
host: process.env.DB_HOST || '127.0.0.1',
user: process.env.DB_USER || 'local_user',
password: process.env.DB_PASSWORD || 'local_password',
database: process.env.DB_NAME || 'local_database',
multipleStatements: true,
charset: 'utf8mb4' // necessary if you might need support for emoji characters
});
connection.on('connection', function (connection) {
// handy for testing
console.log('Pool id %d connected', connection.threadId);
});
connection.on('enqueue', function () {
// handy for testing
console.log('Waiting for available connection slot');
});
// make the connection global via the the variable db
global.db = connection;
// everywhere else in your app, use the now global db variable when running queries
db.query(
'INSERT INTO users SET ?', [{name: "John Smith"}], function(error, results, fields) {
if (error) throw error;
console.log(results);
});
}
Upvotes: 1