Multiple Route - mySQL Connections

84 views
Skip to first unread message

Grant MacDonald

unread,
May 27, 2015, 12:21:41 PM5/27/15
to node-...@googlegroups.com
Hi folks.  I have a node-mysql app written using the Express 4 framework.  I have multiple routes defined in my main source file (app.js) similar to this:

var customers = require('./routes/routeCustomers');
var programs = require('./routes/routePrograms');
var regions                = require('./routes/routeRegions');

app.use('/customers', customers);
app.use('/programs', programs);
app.use('/regions',              regions);


At the moment I have each of these routes make its own connection to the database.  It works fine but I'm sure this isn't best practice.  I did a search and couldn't find anything to suggest the best way to do this.  I tried making the connection in the app.js file but the connection isn't seen in the routes.  

Any suggestions as to the best way to do this is appreciated.

Thanks. Grant.

Sandro Tchikovani

unread,
Mar 12, 2016, 5:51:39 PM3/12/16
to node-mysql
Hi Grant !

Did you find any resources, best practices for that ?

Thanks,
Sandro

Grant MacDonald

unread,
Mar 13, 2016, 10:57:46 AM3/13/16
to node-mysql
Hi Sandro.  I just left it the way it is (each route connecting to mySql.)  If you find anything please let me know!

Thanks. Grant.

Ryan Lee

unread,
Mar 14, 2016, 5:25:28 AM3/14/16
to node-...@googlegroups.com

The best solution I've come up with is to pass a reference to a mysql connection (or pool) into each route using the app.locals variable:

//app.js
var app = require('express')();
app.locals = {
  'db' : mysql.createPool() // this can also be a connection
}

//a route file
route.get(req, res, next) {
  req.app.locals.db.query(...);
};

This give you an advantage of unit testing your router code. You can pass in a sinon stubbed object as the connection or pooled connection.

Ryan


--
You received this message because you are subscribed to the Google Groups "node-mysql" group.
To unsubscribe from this group and stop receiving emails from it, send an email to node-mysql+...@googlegroups.com.
To post to this group, send email to node-...@googlegroups.com.
Visit this group at https://groups.google.com/group/node-mysql.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages