CabloyJS provides more convenient database transaction support. Let’s look at how database transaction is supported in EggJS and CabloyJS respectively

EggJS

  1. 1const conn = await app.mysql.beginTransaction(); // begin
  2. 2
  3. 3try {
  4. 4 await conn.insert(table, row1); // step one
  5. 5 await conn.update(table, row2); // step two
  6. 6 await conn.commit(); // commit
  7. 7} catch (err) {
  8. 8 // error, rollback
  9. 9 await conn.rollback(); // must rollback on error!!
  10. 10 throw err;
  11. 11}

CabloyJS

In CabloyJS, there is no need to change the code related to accessing the database, just declare the middleware transaction in the API route

src/suite-vendor/test-party/modules/test-party/backend/src/routes.js

  1. 1// test
  2. 2{ method: 'post', path: 'kitchen-sink/guide/echo8', controller: 'testKitchensinkGuide', middlewares: 'transaction' },

Whether ctx.db or model is used to operate the database, when the middleware transaction is enabled, the same database connection object is automatically maintained in the context environment, thus facilitating support for database transaction