Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Currently I'm setting my client connection for node-mysql by doing the following in my app.js and a special config/environment.js:

var client = mysql.createClient({
  user:     'USER',
  database: 'DATABASE',
  password: 'PASSWORD',
  host:     'HOST'
});

app.configure(function(){
  ...
  app.set('client', client);
  ...
});

Then in my client code I just call app.settings.client to use the MySQL client.

I'm not sure if this is the right approach, and it certainly doesn't work when I'm doing testing, as I need a running instance of the app.

Any suggestions?

like image 737
Josh Smith Avatar asked Oct 09 '22 01:10

Josh Smith


1 Answers

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 = ...;

like image 141
alessioalex Avatar answered Oct 13 '22 09:10

alessioalex