NodeJS(v9)-MassiveJS(v5.1)-db.withTransaction

时间:2018-07-10 16:03:07

标签: node.js postgresql transactions massivejs

摘要

据我对使用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}
);

MassiveJS交易文档

https://dmfay.github.io/massive-js/tasks-and-transactions.html

0 个答案:

没有答案