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

EggJS

const conn = await app.mysql.beginTransaction(); // begin

try {
  await conn.insert(table, row1);  // step one
  await conn.update(table, row2);  // step two
  await conn.commit(); // commit
} catch (err) {
  // error, rollback
  await conn.rollback(); // must rollback on error!!
  throw err;
}

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/module/test-party/backend/src/routes.js

// test
{ 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