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 { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 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.