By introducing the transactions, they revert all changes made to the database in the event that the method fails to execute. This helps prevent traces of data considered junk.
classExample {publicasynchandle() {// Creates a queryRunnerconsttrx=Connection.mysql.createQueryRunner();// Creates a single connection to the databaseawaittrx.startTransaction();try { // The trx object is mandatory if there is a connection to a database but optional if you are using "in memory repositories"
constresult=awaitthis.examplesRepository.create({ name:'example' }, trx);// Use after all the logic and before the method returns to persist modifications to the databaseif (trx.isTransactionActive) awaittrx.commitTransaction();return result; } catch (error:unknown) {// In case of execution failure rolls back all changes made to the databaseif (trx.isTransactionActive) awaittrx.rollbackTransaction();throw error; } finally {// Releases the connection so it can be used in other casesif (!trx.isReleased) awaittrx.release(); } }}
There are 13 types of standard queries for all modules, they are fully dynamic so they will respond to 90% of your needs.