据我对使用db.withTransaction
的文档的理解,听起来好像每当诺言被拒绝时,所有tx
查询都会被回滚。但是,我看到诺言确实遭到拒绝时,我的查询仍然存在。我想相信这只是我缺乏理解。
const startChargeTransaction = async function(db, stripe, meta) {
let stripeCharge
try {
// Create a new stripe charge
stripeCharge = await stripe.charges.create({
amount: meta.cost,
currency: 'usd',
source: meta.token.id,
description: meta.description
})
await db.withTransaction(async tx => {
// Store the successful charge in our database
await tx.payments.store_charge({
stripe_id: stripeCharge.id,
amount: meta.cost,
description: meta.description,
user_id: meta.user_id,
sf_id: meta.sf_id
})
// Update the user's enrollment to reflect a successful payment
await tx.query(
`UPDATE enrollments SET ${meta.column_to_update} = TRUE WHERE user_id = ${
meta.user_id
} AND session_id = ${meta.class_session_id}`
)
})
} catch (err) {
console.error('startChargeTransaction failed in payments_controller.js:', err)
await stripe.refunds.create({ charge: stripeCharge.id })
throw new Error(
'startChargeTransaction failed. However, queries were successfully rolled back and the stripe charge was refunded!'
)
}
}
我对表enrollments
的更新查询故意失败,因为表enrollments
不存在。然后,我希望运行charge
时不会在tx.payments.store_charge
表中看到新记录。
即使交易被拒绝,我的charge
表也会填充新记录。
对tx.payments.store_charge
的查询:
INSERT INTO charge (stripe_id, description, amount, status, "createdAt", "updatedAt", user_id, sf_id)
VALUES (
${stripe_id},
${description},
${amount},
'paid',
NOW(),
NOW(),
${user_id},
${sf_id}
);
https://dmfay.github.io/massive-js/tasks-and-transactions.html