egg-sequelize-autotrx
This plugin helps to do transaction auto pass down and solve the nested transaction issue.
Problems
After CLS enabled, nested transaction will have unexpected result:
async { await thisctxmodel}
If error throw out from M4 creation, transaction will rollback creation for M1 and M4. M2 and M3 will be committed. To make all the operations commit and rollback together through out all the transactions, you need help from this plugin.
Internally, this plugin solves the problem by passing parent transaction down to the child transaction:
async { await thisctxmodel}
Install
$ npm i egg-sequelize-autotrx --save
Usage
You need to use egg-sequelize plugin first, and have it CLS enabled with cls-hooked:
single datasource
// config.xx.jsconst mySequelize = const clsNamespace = mySequelize module { const config = exports = {} // use customized sequelize. https://github.com/eggjs/egg-sequelize#customize-sequelize configsequelize = Sequelize: mySequelize dialect: 'mysql' // ... }
multiple datasource
// config.xx.jsconst mySequelize = const clsNamespace = // create multiple namespaces for multiple customized sequelizemySequelize module { const config = exports = {} // for multiple datasource, you need setup CLS of each your specific sequelize with different namespaces. https://github.com/eggjs/egg-sequelize#multiple-datasources configsequelize = Sequelize: mySequelize datasources: delegate: 'model1' dialect: 'mysql' // ... delegate: 'model2' dialect: 'mysql' // ...
enable sequelize-autotrx plugin:
// {app_root}/config/plugin.jsexportssequelizeAutotrx = enable: true package: 'egg-sequelize-autotrx'
Configuration
// {app_root}/config/config.default.jsexportssequelizeAutotrx = // no config required here
see config/config.default.js for more detail.
Example
Let's see a real case:
// controller.jsasync { await thisctxmodel} async { await this} // this transaction can be execute alone, and also can be nested into another transactionasync { await thisctxmodel}
If you need your nested transaction commit by itself, you can do:
async { await thisctxmodel}
Questions & Suggestions
Please open an issue here.