Junior — Middle
Have you had experience using transactions in your projects?
sobes.tech AI
Answer from AI
Yes, in Node.js projects I have used transactions, especially when working with databases such as PostgreSQL or MySQL. Transactions allow grouping multiple operations into a single atomic unit, so that either all changes are applied or none are, which is important for maintaining data integrity.
Example of using a transaction with the pg library for PostgreSQL:
const { Client } = require('pg');
async function performTransaction() {
const client = new Client();
await client.connect();
try {
await client.query('BEGIN');
await client.query('INSERT INTO users(name) VALUES($1)', ['Alice']);
await client.query('INSERT INTO accounts(user_id, balance) VALUES($1, $2)', [1, 100]);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
await client.end();
}
}
Thus, if one operation fails, all changes will be rolled back.