Search code examples
sql-servernode.jstransactionstransactionscope

node.js: Creating a transaction that covers calls to more than one repository


I'm used to code using C# and sometimes I create transactions that have more than one call to different repositorys, and if one that calls fails, the rollback covers every repository.

The code is like this:

using (var scope = new TransactionScope())
{
    itemRepository.deleteItems(items);
    bookRepository.deleteBooks(books);
    scope.Complete();
}

This ensures that if an error occurs on bookRepository, the deleted items will be on the rollback.

Now, I'm trying to do the same thing using node.js. I found the mssql package that has the option to create transactions, but only inside the repository, like this:

var transaction = new sql.Transaction(/* [connection] */);
transaction.begin(function(err) {
// ... error checks 

var request = new sql.Request(transaction);
    request.query('insert into mytable (mycolumn) values (12345)', function(err, recordset) {
        // ... error checks 

        transaction.commit(function(err, recordset) {
            // ... error checks 

            console.log("Transaction committed.");
        });
    });
});

So, there's some way to create a transaction on the Service that covers more than one repository like I described?


Solution

  • you can create a transaction scope using a beautiful framework called Sequelize. If you look the page relative to transactions, you can find a way to pass a transaction to all queries.

     sequelize.transaction(function (t1) {
       // With CLS enabled, the user will be created inside the transaction
       return User.create({ name: 'Alice' });
     });