Cabloy provides more convenient database transaction support. Let’s look at how database transaction is supported in EggJS and Cabloy 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;
}

Cabloy

In Cabloy, there is no need to change the code related to accessing the database, just declare the middleware transaction is enabled on the API route

src/module/test-todo/backend/src/routes.js

// test
- { method: 'post', path: 'test/echo', controller: test },
+ { method: 'post', path: 'test/echo', controller: test, 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