I am wondering if I can pass a connected database instance to an express middleware as an argument.
For example:
// in app.js
const mysql = require('mysql');
const mysqlCon = mysql.createConnection({
// some configurations...
})
mysqlCon.connect((err)=> if(err) throw err);
then in a separate file...
// in a separate file called: login handler
const loginHandler = (req, res, dbCon) => {
// query database and stuff...
}
module.exports = loginHanlder;
then back in app.js passes the established mysql connection into the middleware handler
// back in app.js
// a route
const loginHandler = require('./handlers/loginHanlder.js');
app.get('/login', loginHanlder(req, res, mysqlCon));
Will this work? Or are there a conventionally better way of achieving this goal?