0

So, I have some node code to deal with and I’m hoping someone here can help me refactor it. This is 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); 
    });
  }); 
});

I want to extract the part that runs the query, that is, basically everything inside the express controller action. Except of course, nested inside the callbacks, is express code. How would you refactor this?

4

2 回答 2

0

您可以使用 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);
    }
}
于 2015-12-15T15:04:03.903 回答
0

借助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;
        });
});

你想如何模块化这样的代码取决于你。

于 2015-12-24T04:47:44.550 回答