共享环境不支持数据库事务?
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
var cloud_back = new cloud.Cloud({
resourceAppid: 'xxx',
resourceEnv: 'yyy',
})
await cloud_back.init({
env: cloud_back.DYNAMIC_CURRENT_ENV
})
const db = cloud_back.database({
throwOnNotFound: false
})
const _ = db.command
try {
const result = await db.runTransaction(async transaction => {
const r1 = await transaction.collection('book').doc(event.books[0]._id).get()
const r2 = await transaction.collection('book').doc(event.books[1]._id).get()
if (r1.data && r2.data) {
const u1 = await transaction.collection('book').doc(event.books[0]._id).update({
data: {
available_stock: _.inc(1)
}
})
const u2 = await transaction.collection('book').doc(event.books[1]._id).update({
data: {
available_stock: _.inc(1)
}
})
console.log(`transaction succeeded`)
// 会作为 runTransaction resolve 的结果返回
return {
r1: r1.data.available_stock + 1,
r2: r2.data.available_stock + 1,
}
} else {
// 会作为 runTransaction reject 的结果出去
await transaction.rollback(-100)
}
})
return {
success: true,
Account: result,
}
} catch (e) {
console.error(`transaction error`, e)
return {
success: false,
error: e
}
}
}
B的环境共享给了A(所有权限)
在A的云函数中,访问B的数据库,使用runTransaction创建事务,抛出异常:
{
code: 'SIGN\_PARAM\_INVALID',
message: 'you are not authorized to perform operation (tcb:database.startTransaction)'
}
如果在A的云函数中,改成访问A的数据库,就没有问题。