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


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;


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


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