database - Node.JS 中共享数据库句柄的设计模式

标签 database node.js design-patterns

如何在各个 NodeJS 模块之间共享数据库连接?我发现的示例都具有整体结构,其中整个代码都在一个 app.js 文件中。

/* main.js */
var foo = require("./foo"); 
/* express stuff ...*/
mysql = /* establish mysql connection */ 
app.get("/foo", foo.hello ); 


/* foo.js */
exports.hello = function(req, res) {
   res.send("Hello from the foo module!"); 
}

我如何从我的模块“foo”访问“mysql”?为此推荐的设计模式是什么?

最佳答案

您可以使用模块模式轻松地将数据库对象(以及其他任何内容)传递给需要它的模块。

// users.js
module.exports = function( options ) {
    var db = options.db;
    var pants = options.pants;  // or whatever

    return {
        GetUser: function( userID, callback ) {
            db.query("....", function (err, results) {
                callback(results)
            });
        },
        AnotherFunc: function (...) {},
        AndAnotherFunc: function (...) {}
    };
};

您可以像这样使用此模块:

// make your db connection here

var users = require('./users.js')({
    db: db,
    pants: 'blue'
});

users.GetUser( 32, function( user ) {
    console.log("I got the user!");
    console.log( user );
});

我发现这是编写模块的好方法,因为它很像创建一个实际的 Class 对象,就像在 C++ 中一样。您甚至可以模拟“私有(private)”方法/参数。

关于database - Node.JS 中共享数据库句柄的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20935372/

相关文章:

database - “追随者”和效率

c# - EXEC sp_spaceused 查询

c# - 将更改从一个数据库更新到同一服务器中的另一个数据库

javascript - 直接访问 url 时如何修复 "Cannot read property ' 文档' of undefined"?Next.js 和 apexcharts lib

javascript - 在 Node.js 上的 JS 中,将数据、数组/文件/其他地方的 "a lot"放在哪里

c# - 将一个工厂注入(inject)一个类

python - 如何以模块化的方式设计应用程序?

mysql - 一些流行的基于行和基于列的数据库是什么?

node.js - mongodb, `cursor.exec`是什么意思?

java - 可观察类可以构造为单例吗?