egg-sequelize 如何创建transaction

Created on 1 Dec 2018  ·  2Comments  ·  Source: eggjs/egg

在 egg-sequelize 如何创建transaction?

Most helpful comment

我在实践中是这么用的,免去手动传参

// 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()
})

All 2 comments

    // 事务
    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()
})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

yuu2lee4 picture yuu2lee4  ·  3Comments

dizhifeng picture dizhifeng  ·  3Comments

zhaofinger picture zhaofinger  ·  3Comments

Azard picture Azard  ·  3Comments

Ailein picture Ailein  ·  3Comments