0

我的要求是在sails api v 0.12中提升帆后连接到postgresql的动态数据库。从 angular ui 中,我有一个不同的 DB 值的下拉列表,我将一个参数(dbhostname)发送到 dummycontroller.js 并希望在连接.js 中的 db 字符串名称匹配时连接到那个特定的 db

1)如何将api dummycontroller.js 参数((dbhostname))传递给connections.js 2)如何动态访问connections.js 或models.js 中的db 主机。如果条件将它们放在哪里?

虚拟控制器.js

从 ui 选择下拉列表中,db 值通过 api 触发器传递给 dummycontroller.js

http://localhost:1337/api/dummy/dynamicDb?db=db

module.exports = {
dynamicDb: function (req, res, next) {

    const db= req.query.db;
console.log(db);

const qry = "select * from person where city= "newyork";
console.log(qry);
    dummy.query(qry,function (err, resp) {
            //user = JSON.parse(user);
        if (err) {
          return res.json({
            error: err
          });
        }
        if (resp === undefined) {
          return res.notFound();
        } else
                console.log(resp);
          return res.json({
            userData: resp.rows
          });

      }

    );
        }}

我想捕获 db 值并发送到连接或 models.js 并根据 db 值选择不同的 db 主机,然后在 dummycontroller.js 中触发 db 查询。

4

1 回答 1

0

我在我的 Sails 应用程序中使用 pg 节点模块找到了解决上述情况的方法。在您的应用程序中安装 pg 插件,即 npm install pg。

我在sails 应用控制器中创建了dbconnections.js

const a = {
  host: 'abc.com',
  port: 'xxxx',
  database: 'xxxx',
  user: 'xxxx',
  password: 'xxxx'
}

const b = {
  host: 'ecd.com',
 port: 'xxxx',
  database: 'xxxx',
  user: 'xxxx',
  password: 'xxxx'
}


module.exports = { a: a, b: b};

然后在我的其他控制器中,我使用 pg 插件与通过 api 传递 db env 的用户匹配,即在我的其他控制器中

var sourceFile = require('./dbconnections.js');

const {
      Client
    } = require('pg');

    var match_env;

    for (x in sourceFile) {

      if (x === env) {
        match_env = sourceFile[x];

      }
    }

    const client = new Client(match_env)
 now client object will have all postgresql transactions which one could execute
    client.connect()
    const qry = "select * from person where city= "newyork";
    client.query(qry, function (err, resp) {

    console.log("before", client)

    client.end();
    console.log("after", client)
    //user = JSON.parse(user);
    if (err) {
      return res.json({
        error: err
      });
    }
    if (resp === undefined) {
      return res.notFound();
    } else
      console.log(resp);
    return res.json({
      userData: resp.rows
    });

  }

);


Based on the use case we could move the above code to other js file and call in as 
many controller as we can and this would work with multiple for multiple db 
connections of postgres sql in sails app.
于 2019-08-08T23:41:24.227 回答