Nodejs和TypeORM交易混乱

时间:2019-10-19 17:31:17

标签: javascript node.js sql-server typeorm

我很困惑,无法从TypeORM文档中解决它。

这是我用作请求处理程序的函数,它正在使用从getManager()中获取的事务

static makeTransaction = async (req: Request, res: Response) => {
    try {
        // check if the account ids are same
        const { senderAccountId, receiverAccountId, amount } = req.body;

        let senderAccount = await findEntityById(getRepository(Account), senderAccountId);
        let receiverAccount = await findEntityById(getRepository(Account), receiverAccountId);
        senderAccount.balance -= amount;
        receiverAccount.balance += amount;
        await validateOrReject(senderAccount);
        await validateOrReject(receiverAccount);
        const tempEntity = MyEntity.create({
            amount,
            receiverAccount: receiverAccount,
            senderAccount: senderAccount,
        });

        await validateOrReject(tempEntity);

        const accounts = await getManager().transaction(async transactionManager => {
            await transactionManager.save(senderAccount);
            await transactionManager.save(receiverAccount);

            return transactionManager.save(tempEntity);
        });

        return res.status(200).json({
            error: null,
            data: true,
        });
    } catch (e) {
        return res.status(400).json({ error: "Transaction wasn't successfull" });
    }
};

因此,当我为最后一次保存放置一个catch函数时(只有它失败,并且其中的前2个正确运行),它会显示“查询运行器已发布。无法再运行查询”错误。

当我像这样更改流程时,它起作用了,我真的很想知道原因,因为在documents中有针对不同实体类型的保存操作,这也是我正在尝试做的事情。

static makeTransaction = async (req: Request, res: Response) => {
    try {
        // check if the account ids are same
        const { senderAccountId, receiverAccountId, amount } = req.body;

        let senderAccount = await findEntityById(getRepository(Account), senderAccountId);
        let receiverAccount = await findEntityById(getRepository(Account), receiverAccountId);
        senderAccount.balance -= amount;
        receiverAccount.balance += amount;
        await validateOrReject(senderAccount);
        await validateOrReject(receiverAccount);
        const tempEntity = MyEntity.create({
            amount,
            receiverAccount,
            senderAccount,
        });
        await validateOrReject(tempEntity);

        const transactionRes = await getManager().transaction(async transactionManager => {
            return transactionManager.save([tempEntity, senderAccount, receiverAccount]);
        });

        return res.status(200).json({
            error: null,
            data: transactionRes[0],
        });
    } catch (e) {
        console.log(e);
        return res.status(400).json({ error: "Transaction wasn't successfull" });
    }
};

我想了解原因,并感谢任何想法或帮助,谢谢。

0 个答案:

没有答案