【问题标题】:Creating a transaction with node-pg and Express?使用 node-pg 和 Express 创建交易?
【发布时间】:2021-02-25 00:10:15
【问题描述】:

我正在尝试在 Express API 中使用 node-postgres 编写 TRANSACTION。 [下面的代码按预期工作,主要是寻找应该更正/更改的内容]

这将是一个POST 请求,它创建一个“事务”并更新单独表中的记录。所以基本上一次有几个查询。下面是代码:

对于上下文,db 是一个到 postgres 数据库的连接池。

// @desc        Add a Transaction
// @route       DELETE /api/v1/envelopes/:id/transactions
exports.addEnvelopeTransaction = async (req, res) => {
    const { id } = req.params;
    const { title, amount } = req.body;
    const date = new Date();

    const envelopeQuery  = "SELECT * FROM envelopes WHERE envelopes.id = $1";
    const transactionQuery = "INSERT INTO transactions(title, amount, date, envelope_id)VALUES($1, $2, $3, $4) RETURNING *";
    const updateEnvQuery = "UPDATE envelopes SET budget = budget - $1 WHERE id = $2 RETURNING *";

  try {
        // Use SQL TRANSACTION
        await db.query('BEGIN');
        const envelope = await db.query(envelopeQuery, [id])
        if (envelope.rowCount < 1) {
      return res.status(404).send({
        message: "No envelope information found",
            });
        };
        const newTransaction = await db.query(transactionQuery, [title, amount, date, id]);
        await db.query(updateEnvQuery, [amount, id]);
        await db.query('COMMIT');
        res.status(201).send({
            status: 'Success',
            message: 'New transaction created',
            data: newTransaction.rows[0],
            });
  } catch (err) {
        await db.query('ROLLBACK');
    return res.status(500).send({
            error: err.message
        });
  }
};

我在这里闻到了一些糟糕的代码,我真的不知道我是否在适当的地方使用了BEGINCOMMITROLLBACK

我应该改变什么?

【问题讨论】:

标签: node.js postgresql api rest express


【解决方案1】:

代码本身可以工作,但正如您已经指出的那样,它并不干净。

我建议您使用某种查询构建器(轻量级库例如是 knex.js (http://knexjs.org/) - 可以在此处找到如何处理事务的示例 -> http://knexjs.org/#Builder-transactingnode-postgres 库。

【讨论】:

    猜你喜欢
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2019-07-06
    • 2019-02-05
    • 2017-07-27
    • 1970-01-01
    • 2012-08-22
    相关资源
    最近更新 更多