3

我正在使用需要在数据库中插入 3次的NodeJS/Postgres构建一个简单的 web 应用程序。

为了控制我正在使用的语句链pg-transaction

我的问题是我必须始终运行 2 个第一个 INSERTS,但我有条件运行第 3 个。

也许我的代码可以以更好的方式构建(欢迎提出建议)。

这是一个伪代码:

function(req, res) {
  var tx = new Transaction(client);
  tx.on('error', die);
  tx.begin();
  
  tx.query('INSERT_1 VALUES(...) RETURNING id', paramValues, function(err, result) {
    if (err) {
      tx.rollback();
      res.send("Something was wrong!");
      return;
    }
    
    var paramValues2 = result.rows[0].id;
    tx.query('INSERT_2 VALUES(...)', paramValues2, function(err2, result2) {
      if (err) {
        tx.rollback();
        res.send("Something was wrong!");
        return;
      }
      
      // HERE'S THE PROBLEM (I don't want to always run this last statement)
      // If I don't run it, I will miss tx.commit()
      if (req.body.value != null) {
        tx.query('INSERT_3 VALUES(...)', paramValues3, function(err3, result3) {
          if (err) {
            tx.rollback();
            res.send("Something was wrong!");
            return;
          }
        
          tx.commit();
          res.send("Everything fine!");
        });
      }
    });
  });
}

每次查询后重复三次相同的if (err) {}看起来很丑陋。

试图检查一些选项我发现了 Sequelize,但看不到用它解决这个问题的方法。

欢迎任何建议!

谢谢!

4

1 回答 1

4

手动事务管理是一条危险的道路,尽量避开它!;)

下面是如何在pg-promise的帮助下正确地做到这一点:

function(req, res) {
    db.tx(t => { // automatic BEGIN
            return t.one('INSERT_1 VALUES(...) RETURNING id', paramValues)
                .then(data => {
                    var q = t.none('INSERT_2 VALUES(...)', data.id);
                    if (req.body.value != null) {
                        return q.then(()=> t.none('INSERT_3 VALUES(...)', data.id));
                    }
                    return q;
                });
        })
        .then(data => {
            res.send("Everything's fine!"); // automatic COMMIT was executed
        })
        .catch(error => {
            res.send("Something is wrong!"); // automatic ROLLBACK was executed
        });
}

或者,如果您更喜欢 ES7 语法:

function (req, res) {
    db.tx(async t => { // automatic BEGIN
            let data = await t.one('INSERT_1 VALUES(...) RETURNING id', paramValues);
            let q = await t.none('INSERT_2 VALUES(...)', data.id);
            if (req.body.value != null) {
                return await t.none('INSERT_3 VALUES(...)', data.id);
            }
            return q;
        })
        .then(data => {
            res.send("Everything's fine!"); // automatic COMMIT was executed
        })
        .catch(error => {
            res.send("Something is wrong!"); // automatic ROLLBACK was executed
        });
}

更新

async在示例中用 ES7 /替换了 ES6 生成器await,因为 pg-promise 从 9.0.0 版本开始停止支持 ES6 生成器

于 2016-05-05T15:16:36.670 回答