May 20, 2021 WeChat Mini Program Development Document
Support side: Cloud function
To start a transaction, another API that you can also use to initiate a transaction is runTransaction. Can only be used in cloud functions.
The result of resolve is a transaction operation object, which can manipulate the database through the collection API and end or terminate the transaction through commit or rollback.
Transactions are now only supported in the cloud function wx-server-sdk. Transaction operations are efficient and available, allowing only single-record operations, not bulk operations, but multiple records can be operated in a single transaction.
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 transaction = await db.startTransaction()
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)
}
})
await transaction.commit()
console.log(`transaction succeeded`)
return {
success: true,
aaaAccount: aaaRes.data.amount - 10,
}
} else {
await transaction.rollback()
return {
success: false,
error: `rollback`,
rollbackCode: -100,
}
}
} catch (e) {
console.error(`transaction error`, e)
return {
success: false,
error: e
}
}
}