Eddie Lam
Eddie Lam

Reputation: 619

Passing a mysql connection to expression routing middleware function as argument


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?

Upvotes: 1

Views: 677

Answers (1)

eol
eol

Reputation: 24565

The way you're trying to do it won't work, as req,res will be undefined.

However, you could create a factory function that takes the connection as a parameter and retours a route-handler function. Since the function that will be returned is a closure, it will have access to the db-connection in the parent scope. Something like:

function getRequestHandler(dbConn) {
        return function (req, res, next) {
            // use dbConn here to do stuff
        }
}

You can use it like this:

const dbConn = initConnection(); // connect to your db here and return the connection instance
app.get('/login', getRequestHandler(dbConn));

Alternatively, if you don't want/need to create your own factory function, you can simply do:

app.get('/login', (req, res) => loginHandler(req, res, mysqlCon));

Upvotes: 1

Related Questions