如何在 Sails.js 中动态连接到数据库

How to dynamically connect to databases in Sails.js

我正在使用 nodejs 重建遗留 PHP 应用程序,经过大约一周的探索后我选择了 sailsjs。一切都很好,直到我意识到在帆中你只能访问控制器中的 session 变量。因此,我无法与模型建立动态连接。

旧版应用程序使用 PHP session 全局变量在身份验证后连接到不同的 postgresql 数据库,我似乎无法在网上找到解决方法。我在网络上看到过类似的问题。有 node/sails/database 极客吗?

我正在考虑使用 sails 进行身份验证,因为它已经可以工作并使用 expressjs 来实现我的 sails 应用程序随后将通过以某种形式的微服务架构发送数据库连接参数来调用的服务。

目前 运行 在 localhost:1337 航行,我的快递在 localhost:3000。这是一个好方法吗?

我认为您不能动态更改模型中定义的 connection 属性。但是,您可以尝试不在连接将动态更改的模型中设置任何连接,并根据用户设置默认配置连接。像这样的东西:

User.find(1, function(err, user){

    connection = select_connection_for_phones(user);

    // changing the model connection dinamically
    // You should not define any connection in the model.
    sails.config.models.connection = connection;
    Phone.find({user : user.id }, do_something_else);

});

这样,您的 select_connection_for_phones 将收到用户和 return 字符串连接,为模型设置全局配置连接,然后开始查询。如果您的模型 Phone 没有定义连接,它将使用默认值。

相反的方式,可能是这样的:

User.find(1, function(err, user){

    connection = select_connection_for_phones(user);

    // changing properties of the postgresql connection.
    // You must define all your models with this connection.
    sails.config.connections.postgresql.host = host_from_user(user);
    sails.config.connections.postgresql.port = port_from_user(user);
    Phone.find({user : user.id }, do_something_else);

});

在这种情况下,您应该使用相同的连接设置模型,并动态更改连接的属性。

我在这里回答我自己的问题,这里也有人问过类似的问题,none 提供的答案似乎有效。我没有在我的模型中使用水线,而是成功地使用了 pg 模块,

$ npm install pg --save
var pg = require('pg');

通过这种方式,我可以动态地将连接字符串从我的控制器传递到我的模型,而忽略水线 ORM。

我创建了一个 sails 服务来为每个会话获取和设置数据库连接字符串。

然后对于每个查询,我传递存储在会话中的连接字符串:

var sessionConnection = ConnectionsService.getSessionConnection(req,res);

  pg.connect(sessionConnection, function(err, client, done) {
     // do connection stuff and queries here

  });

希望这对其他人有帮助

我从 sails-postgresql v0.11.4 创建了一个带有额外功能的 sails 适配器。 https://www.npmjs.com/package/sails-postgresql-pp