0
0
NestJSframework~30 mins

Transactions in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Transactions in NestJS
📖 Scenario: You are building a simple NestJS service to manage bank accounts. You want to ensure that money transfers between accounts happen safely using transactions, so that either both accounts update correctly or none do.
🎯 Goal: Build a NestJS service method that uses transactions to transfer money between two accounts safely.
📋 What You'll Learn
Create an initial accounts data structure with two accounts and their balances
Add a variable to hold the transfer amount
Write a service method that uses a transaction to update both accounts
Complete the transaction handling with commit and rollback logic
💡 Why This Matters
🌍 Real World
Transactions ensure that money transfers between accounts happen safely without data loss or corruption.
💼 Career
Understanding transactions is essential for backend developers working with databases and NestJS to build reliable financial or data-critical applications.
Progress0 / 4 steps
1
Create initial accounts data
Create a variable called accounts as a JavaScript object with two keys: accountA with value 1000 and accountB with value 500.
NestJS
Need a hint?

Use a JavaScript object with keys accountA and accountB and assign the given balances.

2
Add transfer amount variable
Add a constant variable called transferAmount and set it to 200.
NestJS
Need a hint?

Use const transferAmount = 200; to define the amount to transfer.

3
Write transfer method with transaction
Write an async function called transferMoney that accepts no parameters. Inside, use a try block to simulate starting a transaction by logging 'Transaction started'. Then subtract transferAmount from accounts.accountA and add it to accounts.accountB. After that, log 'Transaction committed'. Add a catch block that logs 'Transaction rolled back' if an error occurs.
NestJS
Need a hint?

Use try and catch blocks inside an async function to simulate transaction behavior.

4
Complete transaction with NestJS style
Modify the transferMoney function to accept a queryRunner parameter. Use await queryRunner.startTransaction() at the start, then update the accounts. After updating, use await queryRunner.commitTransaction(). In the catch block, use await queryRunner.rollbackTransaction(). Finally, use await queryRunner.release() in a finally block.
NestJS
Need a hint?

Use await with queryRunner methods to handle the transaction lifecycle properly.