typescript
37 lines · 7 steps
Wrapping requests in a transaction with NestJS
A NestJS interceptor opens a database transaction per request and commits, rolls back, or releases it based on the handler's outcome.
Explained by
highlit
1import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
2import { Observable, catchError, concatMap, finalize } from 'rxjs';
3import { DataSource, QueryRunner } from 'typeorm';
4
5declare module 'express' {
6 interface Request {
7 queryRunner?: QueryRunner;
8 }
9}
10
11@Injectable()
12export class TransactionInterceptor implements NestInterceptor {
13 constructor(private readonly dataSource: DataSource) {}
14
15 async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
16 const request = context.switchToHttp().getRequest();
17 const queryRunner = this.dataSource.createQueryRunner();
18
19 await queryRunner.connect();
20 await queryRunner.startTransaction();
21 request.queryRunner = queryRunner;
22
23 return next.handle().pipe(
24 concatMap(async (data) => {
25 await queryRunner.commitTransaction();
26 return data;
27 }),
28 catchError(async (err) => {
29 await queryRunner.rollbackTransaction();
30 throw err;
31 }),
32 finalize(() => {
33 void queryRunner.release();
34 }),
35 );
36 }
37}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Interceptors can wrap the entire request lifecycle, running setup before the handler and teardown after its result stream resolves.
- 2RxJS operators let you branch cleanup logic on success versus error while guaranteeing a final release regardless of outcome.
- 3Attaching a per-request QueryRunner to the request object hands the same transactional connection to downstream handlers.
Related explainers
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
Intermediate
8 steps
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js'; export interface NormalizedPhone { e164: string;
Normalizing phone numbers to E.164 in TypeScript
validation
normalization
error-handling
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/wrapping-requests-in-a-transaction-with-nestjs-explained-typescript-4fbc/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.