我应该在Node.js(Express)应用程序中定义我的MySQL客户端?
目前我正在通过在我的app.js
和特殊的config/environment.js
执行以下步骤来设置node-mysql
的客户端连接:
var client = mysql.createClient({ user: 'USER', database: 'DATABASE', password: 'PASSWORD', host: 'HOST' }); app.configure(function(){ ... app.set('client', client); ... });
然后在我的客户端代码中,我只是调用app.settings.client
来使用MySQL客户端。
我不确定这是否是正确的方法,而且当我进行testing时肯定不起作用,因为我需要一个运行的应用程序实例。
有什么build议么?
我看到它有三种解决scheme:
a)作为@Raynos在评论中build议,使用app.set(key, value);
设置一个数据库值,然后app.set(键)来获得该值。
b)将你的路由包装成一个接受数据库作为参数的函数。 例:
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)创build一个全局variables,可以随处访问(不推荐): global.MY_DB = ...;
我认为这样做更典型的方法是定义一个简单的中间件,将mysql客户端设置为请求的属性。 例如:
var client = mysql.createClient({ user: 'USER', database: 'DATABASE', password: 'PASSWORD', host: 'HOST' }) app.use(function(req, res, next) { req.mysql = client; next(); });
然后在你的路由处理程序中,你可以访问req.mysql
。 在你的testing用例中,你只需要以某种方式设置req.mysql
,它应该很容易。