0
0
NestJSframework~5 mins

Transactions in NestJS

Choose your learning style9 modes available
Introduction

Transactions help keep your data safe by making sure a group of actions all finish together or none at all.

When saving multiple related records that must all succeed or fail together.
When updating several tables and you want to avoid partial changes.
When transferring money between accounts to prevent losing or duplicating funds.
When deleting data that affects other connected data and you want to keep consistency.
Syntax
NestJS
await connection.transaction(async (manager) => {
  // your database operations here
});
Use the transaction method from your database connection to run multiple operations safely.
Inside the transaction callback, use the provided manager to perform database actions.
Examples
This example saves a user and their profile together. If one save fails, none are saved.
NestJS
await connection.transaction(async (manager) => {
  await manager.save(user);
  await manager.save(profile);
});
This example updates an account balance inside a transaction to keep data safe.
NestJS
await connection.transaction(async (manager) => {
  const account = await manager.findOne(Account, { id: 1 });
  account.balance -= 100;
  await manager.save(account);
});
Sample Program

This service method creates a user and their profile inside a transaction. If saving either fails, no data is saved.

NestJS
import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UserService {
  constructor(private dataSource: DataSource) {}

  async createUserWithProfile(userData, profileData) {
    return await this.dataSource.transaction(async (manager) => {
      const user = manager.create(User, userData);
      await manager.save(user);

      const profile = manager.create('Profile', { ...profileData, user });
      await manager.save(profile);

      return user;
    });
  }
}
OutputSuccess
Important Notes

Always use the transaction manager for all database operations inside the transaction callback.

Transactions help prevent data errors when multiple related changes happen together.

Summary

Transactions group multiple database actions to succeed or fail as one.

Use the transaction method from your DataSource in NestJS with an async callback.

Inside the callback, use the provided manager to run your database commands.