1

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?

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

2 Comments

I need to research what factory functions are; anyway, will the following code work, if I provide the request and response object like this? app.get('/login', (req, res)=> loginHanlder(req, res, mysqlCon));
It's just a fancy name for a function that returns another function :) Yes, this way it should work. It's basically the same thing I did.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.