Where should I define my MySQL client in a Node.js (Express) app? Where should I define my MySQL client in a Node.js (Express) app? express express

Where should I define my MySQL client in a Node.js (Express) app?


There are 3 solutions the way I see it:

a) As @Raynos suggested in the comments, use app.set(key, value); to set a db value and then app.set(key) to get that value.
b) Wrap your routes into a function that accepts the database as a parameter. Example:

sample_route.js

module.exports = function (db) {  return function(req, res, next) {    // db is accessible here  }}

app.js

var = sample_route = require('./sample_route')(db);app.get('/sample', sample_route);


c) Make a global variable that will be accessible everywhere (not recommended though): global.MY_DB = ...;


I think that a more typical way to do this would be to define a simple middleware that sets the mysql client as a property of the request. For example:

var client = mysql.createClient({      user:     'USER',      database: 'DATABASE',      password: 'PASSWORD',      host:     'HOST'    })app.use(function(req, res, next) {    req.mysql = client;    next();});

Then in your route handlers you can access req.mysql. In your test cases you just need to set up req.mysql in some way, it should be pretty easy.