Instrução INSERT opcional na cadeia de transações usando NodeJS e Postgres
Estou construindo um webapp simples usandoNodeJS / Postgres que precisa fazer 3 inserções no banco de dados.
Para controlar a cadeia de instruções que estou usandotransação-pg.
Meu problema é que sempre tenho que executar os 2 primeiros INSERTOS, mas tenho uma condição para executar o 3º.
Talvez meu código possa ser construído de uma maneira melhor (sugestões são bem-vindas).
Aqui está um pseudo-código:
function(req, res) {
var tx = new Transaction(client);
tx.on('error', die);
tx.begin();
tx.query('INSERT_1 VALUES(...) RETURNING id', paramValues, function(err, result) {
if (err) {
tx.rollback();
res.send("Something was wrong!");
return;
}
var paramValues2 = result.rows[0].id;
tx.query('INSERT_2 VALUES(...)', paramValues2, function(err2, result2) {
if (err) {
tx.rollback();
res.send("Something was wrong!");
return;
}
// HERE'S THE PROBLEM (I don't want to run it always this last statement)
// If I don't run it, I will miss tx.commit()
if (req.body.value != null) {
tx.query('INSERT_3 VALUES(...)', paramValues3, function(err3, result3) {
if (err) {
tx.rollback();
res.send("Something was wrong!");
return;
}
tx.commit();
res.send("Everything fine!");
});
}
});
});
}
Parece tão feio repetir três vezes o mesmoif (err) {} após cada consulta.
Tentando verificar algumas opções que encontreiSequelizar, mas não conseguiu encontrar uma maneira de resolver esse problema.
Todas as sugestões são bem-vindas!
Obrigado!