简体   繁体   中英

Express - Passing mysql connection to scripts

我定义了mysql连接,其中包含所需的所有参数,默认情况下,如何仅使用client.query(..)使routes/默认情况下的其他脚本可见,而无需或重新定义mysql参数?

A pattern I use is to set up my db object in a module once and export it: (let's call it 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;

And then I can require the db object everywhere I need it. Since require s are cached, this does't actually call the setup methods multiple times.

In app.js:

var db = require('./utils/mySQL.js');
...

In models/user.js:

var db = require('../utils/mySQL.js');
...

A final option, which isn't recommended, is to pollute the global namespace. This seems to be the answer you're really after:

//set up your db
...
// and now make it available everywhere:
global.client = db.client

You can now magically use the client object in all your modules, without even requiring it.

There are many reasons globals are bad, though:

  • If your code and other code define globals, they could conflict and overwrite each other.
  • It's hard to find where you defined the db / client object, etc.

You can inject mysql connection into other scripts like this:

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
};

UPDATE:

You can inject several variables same way. Also you still can export methods from module if you need this:

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM