一个service函数里调用其他多个service, 怎么用事务?
我看egg官网事务实例, mysql有一个beginTransactionScope属性,都是用conn去操作insert和update, 那如果是调用其他service函数, 事务应该怎么写?
3 回复
sequelize case,关键点在于把事务 (transaction) t 传递到每一次数据库操作中
try {
// get transaction
transaction = await sequelize.transaction();
await UserModel.create({ owner_id, email, password: sha256Password, password_salt, name, phone, address, level, remark, enable, sms_alarm_enable, email_alarm_enable }, { transaction });
// step 1
await Model.destroy({where: {id}, transaction});
// step 2
await Model.create({}, {transaction});
// commit
await transaction.commit();
} catch (err) {
// Rollback transaction if any errors were encountered
await transaction.rollback();
}
把conn作为参数传递到其他service函数就可以了 比如在service1中开启事务,调用service2中的函数
//service1 const conn = await this.app.mysql.beginTransaction(); try{
await conn.insert(table, row1);
await conn.update(table, row2);
await this.ctx.service.service2.{method}(conn)
await conn.commit();
}catch(err){
await conn.rollback()
throw err;
}
//service2 await conn.insert(table, row3);