【问题标题】:Transaction still autocommit after throw error in GraphQL+Sequelize+CLS在 GraphQL+Sequelize+CLS 中抛出错误后事务仍然自动提交
【发布时间】:2016-04-22 15:29:07
【问题描述】:

我想知道编码中是否有任何部分我做错了。 我正在尝试做一系列的功能和检查,如果有一些条件不满足,我想回滚事务。

我指的是stackoverflow的参考

我的事务在抛出新错误后仍然被提交。

这是我的示例编码。

//db.js
import Sequelize from 'sequelize';
import Cls from 'continuation-local-storage';
Sequelize.cls = Cls.createNamespace('db');
const Conn = new Sequelize(
    'relay',
    'postgres',
    'tec832',
    {
    dialect: 'postgres',
        host: 'localhost'
    }
);
module.exports.Db = Conn;

在 schema.js 我有

Db.transaction({autocommit: false}).then(()=>{
    args = {vcTitle: {$ilike: `Sample title by Nick`}};
    return testDelPostPromiseNoTran(args).then(obResult => {
        throw new Error("Wrong account type");
    })
});

function testDelPostPromiseNoTran(args){
    return new Promise((resolve, reject) => {
        resolve(delDataNoTran('Post', args));
    });
}

//I am trying to do a standard delete
function delDataNoTran(vcTbName, args){
    return Db.models[vcTbName].destroy({where: args})
    .then(result =>{
        if(result > 0){
            return true;
        }else{
            return false;
        }
    })
    .error(obStatus =>{
        return false;
    });
}

【问题讨论】:

    标签: postgresql transactions sequelize.js graphql


    【解决方案1】:

    您的代码存在一些问题:

    Db.transaction({autocommit: false}).then(()=>{
        args = {vcTitle: {$ilike: `Sample title by Nick`}};
        return testDelPostPromiseNoTran(args).then(obResult => {
            throw new Error("Wrong account type");
        })
    });
    

    应该是……

    Db.transaction(()=>{
        args = {vcTitle: {$ilike: `Sample title by Nick`}};
        return testDelPostPromiseNoTran(args).then(obResult => {
            throw new Error("Wrong account type");
        })
    });
    

    您应该将一个函数传递给Db.transaction。将它放在.then() 块内意味着它在事务之后运行,因此不包含在事务内。这是你的主要问题。

    function testDelPostPromiseNoTran(args){
        return new Promise((resolve, reject) => {
            resolve(delDataNoTran('Post', args));
        });
    }
    

    ...返回一个总是解决的承诺。这是多余的,因为delDataNoTran 已经返回了一个承诺——没有理由将它包装在另一个承诺中。

    args = {vcTitle: {$ilike: `Sample title by Nick`}};
    

    “ilike”应该是“iLike”(区分大小写。)

    我建议花一些时间阅读Sequelize docs

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 2019-09-20
      • 1970-01-01
      • 2015-11-07
      • 2015-11-12
      相关资源
      最近更新 更多