在 egg-sequelize 如何创建transaction?
// 事务
const transaction: any = await this.ctx.model.transaction();
try {
transaction.isolationLevel = this.ctx.model.Sequelize.Transaction.ISOLATION_LEVELS[!_.isUndefined(obj.isolationLevel) ? obj.isolationLevel : 'READ_COMMITTED'];
// const data: any = await obj.commit(transaction);
await transaction.commit();
return data;
} catch(err) {
await transaction.rollback();
this.ctx.logger.error('=====Error=====Transaction=====>', err);
return obj.error;
}
我在实践中是这么用的,免去手动传参
// config/config.xx.js
const specSequelize = require('sequelize')
// 使用 cls-hooked 才能支持在 sequelize 的事务中使用 async/await
const sequelizeCLSNamespace = require('cls-hooked').createNamespace('your-namespace')
specSequelize.useCLS(sequelizeCLSNamespace)
// ...
config.sequelize = {
// ...
Sequelize: specSequelize
}
使用的时候
await this.ctx.model.transaction(async () => {
await model.XX.xx()
await model.YY.xx()
})
Most helpful comment
我在实践中是这么用的,免去手动传参
使用的时候