Skip to content

nestjs-transaction makes managing database transactions in NestJS easy and straightforward

Notifications You must be signed in to change notification settings

hodfords-solutions/nestjs-transaction

Folders and files

NameName
Last commit message
Last commit date
Sep 23, 2024
Aug 28, 2024
Sep 23, 2024
Sep 24, 2024
Apr 15, 2022
Jan 31, 2024
Nov 2, 2022
Sep 23, 2024
Aug 27, 2024
Sep 23, 2024
Sep 24, 2024
Mar 18, 2025
Mar 18, 2025
Sep 23, 2024
Jan 31, 2024
Sep 23, 2024

Repository files navigation

Hodfords Logo

nestjs-transaction makes managing database transactions in NestJS easy and straightforward. It provides simple tools to start, commit, and roll back transactions, helping you ensure that multiple database operations are completed successfully or not at all. With `nestjs-transaction`, you can handle complex transaction scenarios with ease, making your data handling more reliable and error-free.

Installation πŸ€–

Install the nestjs-transaction package with:

npm install @hodfords/nestjs-transaction --save

Usage πŸš€

First, extend the TransactionService imported from the library in your service, and then use the withTransaction method within the transaction callback to call your service.

How to use

your-service.service.ts
@Injectable()
export class YourService extends TransactionService {
    public constructor(
        @InjectRepository(YourRepository) private repository: Repository<Entity>,
        private yourCustomRepository: CustomRepository,
        private yourService: Service,
        // Let's say you don't want to rebuild this service in the transaction
        private yourCacheService: CacheService,
        @Inject(forwardRef(() => ForwardService)) private yourForwardService: ForwardService
    ) {
        super();
    }

    async theMethodWillUseTransaction(payload: SomePayload) {
        // logic code here
    }
}
your-controller.controller.ts
import { DataSource } from 'typeorm';

@Controller()
export class SomeController {
    constructor(
        private readonly yourService: YourService,
        private dataSource: DataSource
    ) {}

    async method(payload: SomePayload): Promise<SomeResponse> {
        return this.dataSource.transaction(async (entityManager) => {
            return await this.yourService
                .withTransaction(entityManager, { excluded: [CacheService] })
                .theMethodWillUseTransaction(payload);
        });
    }
}

Exclude services from transaction

You can configure services to be excluded from transactions by specifying them in transactionConfig and importing it into AppModule

export const transactionConfig = TransactionModule.forRoot([MailService, I18nService, StorageService, DataSource]);

License πŸ“

This project is licensed under the MIT License