【发布时间】: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
});
}
};
我在这里闻到了一些糟糕的代码,我真的不知道我是否在适当的地方使用了BEGIN、COMMIT 和ROLLBACK。
我应该改变什么?
【问题讨论】:
-
化妆品清理
-
帖子已经cross-posted on CR。
标签: node.js postgresql api rest express