Build HTTP APIs with routing, middleware, validation, controllers, and error handling.
Lessons
Group writes so they all commit or all roll back.
Database Transactions is easiest to learn by reading the example, changing it, and observing the result.
import pg from 'pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [50, 1]);
await client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [50, 2]);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}Practice the Database Transactions example in a small scratch file, then explain what changed and why.