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?
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 = ...;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With