Introduction
Transactions help keep your data safe by making sure a group of actions all finish together or none at all.
Transactions help keep your data safe by making sure a group of actions all finish together or none at all.
await connection.transaction(async (manager) => { // your database operations here });
await connection.transaction(async (manager) => { await manager.save(user); await manager.save(profile); });
await connection.transaction(async (manager) => { const account = await manager.findOne(Account, { id: 1 }); account.balance -= 100; await manager.save(account); });
This service method creates a user and their profile inside a transaction. If saving either fails, no data is saved.
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; }); } }
Always use the transaction manager for all database operations inside the transaction callback.
Transactions help prevent data errors when multiple related changes happen together.
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.
await dataSource.transaction(async (manager) => {
await manager.save(user1);
await manager.save(user2); // throws error
});
console.log('Transaction complete');await dataSource.transaction(async (manager) => {
manager.save(user1);
await manager.save(user2);
});async updateEntities(entityA, entityB) {
await this.dataSource.transaction(async (manager) => {
await manager.save(entityA);
await manager.save(entityB);
});
}
What is the best practice to handle errors and maintain data consistency?Pass the test and this pattern moves unknown