Optional INSERT statement in transaction chain using NodeJS and Postgres

前端 未结 1 1714
抹茶落季
抹茶落季 2020-12-19 22:59

I\'m building a simple webapp using NodeJS/Postgres that needs to make 3 insertions in the database.

To control the chain of statements I\'m using <

相关标签:
1条回答
  • 2020-12-19 23:38

    Manual transaction management is a treacherous path, try to steer away from that! ;)

    Here's how to do it properly, with the help of pg-promise:

    function(req, res) {
        db.tx(t => { // automatic BEGIN
                return t.one('INSERT_1 VALUES(...) RETURNING id', paramValues)
                    .then(data => {
                        var q = t.none('INSERT_2 VALUES(...)', data.id);
                        if (req.body.value != null) {
                            return q.then(()=> t.none('INSERT_3 VALUES(...)', data.id));
                        }
                        return q;
                    });
            })
            .then(data => {
                res.send("Everything's fine!"); // automatic COMMIT was executed
            })
            .catch(error => {
                res.send("Something is wrong!"); // automatic ROLLBACK was executed
            });
    }
    

    Or, if you prefer ES7 syntax:

    function (req, res) {
        db.tx(async t => { // automatic BEGIN
                let data = await t.one('INSERT_1 VALUES(...) RETURNING id', paramValues);
                let q = await t.none('INSERT_2 VALUES(...)', data.id);
                if (req.body.value != null) {
                    return await t.none('INSERT_3 VALUES(...)', data.id);
                }
                return q;
            })
            .then(data => {
                res.send("Everything's fine!"); // automatic COMMIT was executed
            })
            .catch(error => {
                res.send("Something is wrong!"); // automatic ROLLBACK was executed
            });
    }
    

    UPDATE

    Replaced ES6 generators with ES7 async/await in the example, because pg-promise stopped supporting ES6 generators from version 9.0.0

    0 讨论(0)
提交回复
热议问题