[英]Express - Passing mysql connection to scripts
我定义了mysql连接,其中包含app.js
所需的所有参数,默认情况下,如何仅使用client.query(..)
使默认情况下的其他脚本可见,而无需或重新定义mysql参数?
我使用的一种模式是在模块中一次设置db
对象并导出它:(我们称它为utils/mySQL.js
)
//I haven't used real mysql in node so excuse the pseudo-syntax:
var db = require('mysql-driver-thingy');
db.connect('localhost', 'sqlport', options...);
db.otherSetupFunctions();
console.log("Finished db setup. You should only see this message once! Cool.");
module.exports = db;
然后我可以在需要的任何地方使用db
对象。 由于require
是被缓存的,因此实际上并不会多次调用设置方法。
在app.js中:
var db = require('./utils/mySQL.js');
...
在models / user.js中:
var db = require('../utils/mySQL.js');
...
不建议使用的最后一个选择是污染全局名称空间。 这似乎是您真正追求的答案:
//set up your db
...
// and now make it available everywhere:
global.client = db.client
您现在可以在所有模块中神奇地使用客户端对象,甚至不需要它。
但是,有很多原因导致全局变量不佳:
db
/ client
对象的位置,等等。 您可以将mysql连接注入到其他脚本中,如下所示:
app.js
var mysqlConnection = new Conection(params);
require('controller/main.js)(mysqlConnection);
main.js
module.exports = function(mysqlConnection) {
// You can access your mysql connection here
};
更新:
您可以以相同的方式注入多个变量。 如果需要,您仍然可以从模块中导出方法:
app.js
var mysqlConnection = new Conection(params);
var news = require('model/news.js)(app, mysqlConnection);
news.list(function(err, news) {
// Do something
});
news.js
module.exports = function(app, mysqlConnection) {
var methods = {};
// mysql connection and app available from here
methods.list = function(cb) {
mysqlConnection.list(function(err, data) {
cb(err, data);
});
};
return methods;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.