📖 Scenario: You are building a simple banking system where users can transfer money between accounts. To keep data safe, you need to handle transactions properly so that either the whole transfer happens or nothing happens at all.
🎯 Goal: Build a Node.js script that uses a transaction to transfer money between two accounts safely.
📋 What You'll Learn
Create an initial accounts object with two accounts and their balances
Add a variable to hold the transfer amount
Write a function that performs the transfer inside a transaction
Complete the transaction handling with commit and rollback logic
💡 Why This Matters
🌍 Real World
Handling transactions is crucial in banking and e-commerce to keep data consistent and avoid errors during money transfers or purchases.
💼 Career
Understanding transaction handling is important for backend developers working with databases and APIs to ensure data integrity.
Progress0 / 4 steps
1
Create initial accounts data
Create a constant called accounts as an object with two keys: alice with value 500 and bob with value 300.
Node.js
Hint
Use const accounts = { alice: 500, bob: 300 }; to create the object.
2
Add transfer amount variable
Add a constant called transferAmount and set it to 200.
Node.js
Hint
Use const transferAmount = 200; to set the amount to transfer.
3
Write transfer function with transaction logic
Write an async function called transfer that takes no parameters. Inside it, create a variable transactionActive set to true. Then subtract transferAmount from accounts.alice and add it to accounts.bob. If accounts.alice becomes negative, set transactionActive to false.
Node.js
Hint
Define the function with async function transfer(). Use let transactionActive = true; and update balances. Check if accounts.alice is negative to set transactionActive to false.
4
Complete transaction with commit or rollback
Inside the transfer function, after the balance changes, add an if statement that checks transactionActive. If true, add a comment // Commit transaction. Else, add a comment // Rollback transaction and reset accounts.alice to 500 and accounts.bob to 300.
Node.js
Hint
Use if (transactionActive) { /* commit */ } else { /* rollback */ } and reset balances on rollback.
Practice
(1/5)
1. What is the main purpose of using transactions in Node.js database operations?
easy
A. To ensure multiple database actions succeed or fail together
B. To speed up database queries
C. To create multiple database connections
D. To log database errors automatically
Solution
Step 1: Understand the role of transactions
Transactions group several database actions so they either all succeed or all fail, maintaining data integrity.
Step 2: Compare options
Only To ensure multiple database actions succeed or fail together correctly describes this purpose. Other options describe unrelated features.
Final Answer:
To ensure multiple database actions succeed or fail together -> Option A
Quick Check:
Transaction purpose = group actions for success/failure [OK]
Hint: Transactions keep multiple DB actions atomic and consistent [OK]
Common Mistakes:
Thinking transactions speed up queries
Confusing transactions with connection pooling
Assuming transactions auto-log errors
2. Which of the following is the correct way to start a transaction using a Node.js database client?
easy
A. client.query('START TRANSACTION')
B. client.query('OPEN TRANSACTION')
C. client.query('BEGIN')
D. client.query('INIT TRANSACTION')
Solution
Step 1: Recall standard SQL transaction commands
The standard command to start a transaction is 'BEGIN'.
Step 2: Validate options
Only client.query('BEGIN') uses the correct SQL command 'BEGIN'. Other options are invalid SQL commands.
Final Answer:
client.query('BEGIN') -> Option C
Quick Check:
Start transaction command = BEGIN [OK]
Hint: Use 'BEGIN' to start transactions in SQL [OK]
Common Mistakes:
Using non-standard commands like 'START TRANSACTION'
Confusing transaction start with connection open
Using commands that don't exist in SQL
3. Consider this Node.js code snippet using a PostgreSQL client:
The code correctly uses try-catch to rollback on error.
Step 2: Identify missing error handling for rollback
If the ROLLBACK query itself fails, this code does not catch that error, which can cause unhandled exceptions.
Final Answer:
No error handling for ROLLBACK failure -> Option B
Quick Check:
Rollback errors need separate handling [OK]
Hint: Always handle errors from ROLLBACK queries too [OK]
Common Mistakes:
Assuming ROLLBACK never fails
Placing BEGIN after queries
Putting COMMIT inside catch block
5. You want to perform two related database inserts in Node.js using transactions. Which pattern correctly ensures both inserts succeed or both fail, releasing the client connection properly?