【问题标题】:From express + pg to reusable code : help refactoring从 express + pg 到可重用代码:帮助重构
【发布时间】:2015-12-24 12:47:44
【问题描述】:

所以,我有一些节点代码要处理,我希望这里有人可以帮助我重构它。这是 express + pg:

app.get('/path', function (req, res, next) {
  pg.connect(connectionString, function(err, client, releaseClientToPool) {
    client.query(query, function(err, data) {
      if(err) {
        res.send(tellFrontEndThereIsAnError);
      } else {
        res.send(tellFrontEndYay);
      }
         releaseClientToPool); 
    });
  }); 
});

我想提取运行查询的部分,即基本上是快速控制器操作中的所有内容。当然,嵌套在回调中的是快速代码。你会如何重构它?

【问题讨论】:

    标签: node.js express refactoring node-postgres


    【解决方案1】:

    您可以使用 knex.js 进行查询构建 http://knexjs.org/

    控制器:

    var foo = require('foo');
    
    app.get('/path', function (req, res, next) {
        foo.bar(function(err, result) {
            if(err) res.send('send error to front end');
            else res.send('send your result here to front end');
        });
    }
    

    模块:foo.js

    var knex = require('knex')(dbConfig)
    module.exports = {
        bar: function(callback) {
            knex.select('*')
            .from('table')
            .then(function(result) {
                callback(null, result)
            })
            .catch(callback);
        }
    }
    

    【讨论】:

      【解决方案2】:

      借助pg-promise的例子:

      var pgp = require('pg-promise')(/*options*/);
      var db = pgp('postgres://username:password@host:port/database');
      
      app.get('/path', function (req, res, next) {
          db.query("SELECT * FROM table")
              .then(data=> {
                  // set response with the data;
              })
              .catch(error=> {
                  // set response with the error;
              });
      });
      

      如何模块化此类代码取决于您。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-27
        • 2016-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        相关资源
        最近更新 更多