Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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?

Problem

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?

Problem courtesy of: Josh Smith

Solution

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

Solution courtesy of: alessioalex

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×