I am working on a project where I need to implement transaction to rollback PostgreSQL database durin REST operation using Nodejs. I have implemented transaction separately for GET, PUT and POST methods. Do I need to use transaction once or am i on a right track? Thanks in advance for your help.
I want to ensure my database rollback data if it is needed. I am using pg-promise library to get the result.
db.tx(t => {
return t.batch([
t.query('UPDATE users SET active = $1 WHERE id = $2', [true, 123]),
t.query('INSERT INTO audit(event, id) VALUES($1, $2)', ['activate', 123])
]);
})
.then(data => {
// success;
})
.catch(error => {
// error;
});
Or, should I implement below method?
module.exports = {
// if you can run all migration queries simultaneously
up: ({ sequelize: db }) => db.transaction(transaction => Promise.all([
db.query('...', { transaction }),
db.query('...', { transaction }),
])),
// If you have to wait for every query before executing next one
down: ({ sequelize: db }) => db.transaction(async (transaction) => {
await db.query('...', { transaction });
await db.query('...', { transaction });
}),
};
Thank you in advance.