【问题标题】:node.js: Creating a transaction that covers calls to more than one repositorynode.js:创建一个包含对多个存储库的调用的事务
【发布时间】:2016-07-01 18:51:49
【问题描述】:

我习惯于使用 C# 进行编码,有时我会创建对不同存储库进行多次调用的事务,如果调用失败,则回滚会覆盖每个存储库。

代码是这样的:

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

这样可以确保如果 bookRepository 发生错误,已删除的项目将处于回滚状态。

现在,我正在尝试使用 node.js 做同样的事情。 我发现mssql 包可以选择创建事务,但只能在存储库中,如下所示:

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.");
        });
    });
});

那么,有什么方法可以像我描述的那样在服务上创建一个涵盖多个存储库的事务?

【问题讨论】:

  • 我正在为 mysql + node 寻找类似的答案

标签: sql-server node.js transactions transactionscope


【解决方案1】:

您可以使用名为Sequelize 的漂亮框架创建事务范围。 如果您查看与transactions 相关的页面,您可以找到一种将事务传递给所有查询的方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2011-03-29
    • 2021-10-05
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多