Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The SDK database database initiates the transaction


May 20, 2021 WeChat Mini Program Development Document


Table of contents


Database.runTransaction(callback: function, times: number): Promise<any>

Support side: Cloud function

The transaction is initiated. Can only be used in cloud functions.

Parameters

callback: function

A transaction execution function, between an async asynchronous function or a function that returns Promise

times: number

The transaction executes the most times, by default 3 times, and is not repeated after success, with only the transaction being retried in the event of a conflict and not retried when other exceptions occur

Returns a value

Promise.<any>

The result of resolve is the return value of the callback transaction execution function, and the result of reject is either an exception thrown during transaction.rollback or an incoming value

The description of the transaction execution function

The transaction execution function is passed in by the developer, and the function receives an argument transaction (type definition can be found in Transaction), which provides the collection method and the rollback method. The collection method is used to take a database collection record reference for operations, and the rollback method is used to terminate and roll back transactions if they do not want to continue.

The transaction execution function must be an async asynchronous function or a function that returns Promise, and when the transaction execution function returns, the SDK considers that the user logic is complete and automatically commits the transaction, so it is important to ensure that the user transaction logic is completed before returning or resolveing in the async asynchronous function.

Transaction execution functions can be executed multiple times, are automatically repeated when transaction conflicts are discovered internally, and exit is reported if the set maximum number of executions is exceeded.

The errors that occur in the transaction execution function will consider that transaction failed.

The value returned by the transaction execution function will use the value of the promise resolve returned by Runtrance. Exceptions thrown in the function as the value of the promise reject returned by Runtractions. If Transaction.Rollback is called in the transaction function, it is incorporated into the rollback function.The value of the promise reject returned as RuntiansAction.

limit

The transaction is now only supported in the cloud function WX-Server-SDK.In order to ensure efficiency and concurrency, only a single recording operation is allowed, and a batch operation is not allowed, but multiple records can be operated in one transaction.

Precautions

When the transaction execution function provided by the developer returns normally, the SDK automatically commits the transaction, and do not call the transaction.commit method within the transaction execution function, which is used only when performing transaction operations through db.startTransaction.

The sample code

A simple example of a transfer between two accounts

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
  throwOnNotFound: false,
})
const _ = db.command

exports.main = async (event) => {
  try {
    const result = await db.runTransaction(async transaction => {
      const aaaRes = await transaction.collection('account').doc('aaa').get()
      const bbbRes = await transaction.collection('account').doc('bbb').get()

      if (aaaRes.data && bbbRes.data) {
        const updateAAARes = await transaction.collection('account').doc('aaa').update({
          data: {
            amount: _.inc(-10)
          }
        })

        const updateBBBRes = await transaction.collection('account').doc('bbb').update({
          data: {
            amount: _.inc(10)
          }
        })

        console.log(`transaction succeeded`)

        // 会作为 runTransaction resolve 的结果返回
        return {
          aaaAccount: aaaRes.data.amount - 10,
        }
      } else {
        // 会作为 runTransaction reject 的结果出去
        await transaction.rollback(-100)
      }
    })

    return {
      success: true,
      aaaAccount: result.aaaAccount,
    }
  } catch (e) {
    console.error(`transaction error`, e)

    return {
      success: false,
      error: e
    }
  }
}