Nest.js Tutorial

Serializing the response with Prisma

Marcin Wanago
JavaScriptNestJS

When fetching data from the database, we do not always want to present it to the user in the original form. When working with NestJS, the most popular way of modifying the response is with the class-transformer library. However, using the above library with Prisma requires a bit of work. In this article, we provide examples of how to do that in a clean and easy-to-understand way.

The class-transformer library with TypeORM

When working with libraries such as TypeORM, we create data models that use decorators from both TypeORM and the class-transformer library.

user.entity.ts
1import {
2  Column,
3  Entity,
4  JoinColumn,
5  OneToOne,
6  PrimaryGeneratedColumn,
7} from 'typeorm';
8import { Exclude } from 'class-transformer';
9import Address from './address.entity';
10 
11@Entity()
12class User {
13  @PrimaryGeneratedColumn()
14  public id: number;
15 
16  @Column({ unique: true })
17  public email: string;
18 
19  @Column()
20  public name: string;
21 
22  @OneToOne(() => Address, {
23    eager: true,
24    cascade: true,
25  })
26  @JoinColumn()
27  public address: Address;
28 
29  @Column()
30  @Exclude()
31  public password: string;
32}
33 
34export default User;

Thanks to the above, when we query the database using TypeORM, it returns instances of the User class defined above.

1const user = await this.usersRepository.findOneBy({ email });
2console.log(user instanceof User); // true

When we return instances of our User class through the controller, we can use the ClassSerializerInterceptor built into NestJS.

user.controller.ts
1import {
2  Req,
3  Controller,
4  UseGuards,
5  Get,
6  ClassSerializerInterceptor,
7  UseInterceptors,
8} from '@nestjs/common';
9import RequestWithUser from './requestWithUser.interface';
10import JwtAuthenticationGuard from './jwt-authentication.guard';
11 
12@Controller('authentication')
13@UseInterceptors(ClassSerializerInterceptor)
14export class AuthenticationController {
15  @UseGuards(JwtAuthenticationGuard)
16  @Get()
17  authenticate(@Req() request: RequestWithUser) {
18    return request.user;
19  }
20 
21  // ...
22}
If you want to know more about authenticating with JWT, check out API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies

Under the hood, ClassSerializerInterceptor calls the instanceToPlain from the class-transformer and applies the rules we’ve defined using the decorators. An excellent example is using the @Exclude() decorator to avoid sending the password in the response of our API.

Using Prisma with class-transformer

When working with Prisma, we use the Prisma schema files that are not created using TypeScript.

userSchema.prisma
1model User {
2  id        Int      @id @default(autoincrement())
3  email     String   @unique
4  name      String
5  password  String
6  address   Address? @relation(fields: [addressId], references: [id])
7  addressId Int?     @unique
8  posts     Post[]
9}

Because of that, we don’t have the opportunity to use the decorators from the class-transformer library. When we query our database using Prisma, it returns the User data generated under the hood.

users.service.ts
1import { Injectable } from '@nestjs/common';
2import { PrismaService } from '../prisma/prisma.service';
3import { UserNotFoundException } from './exceptions/userNotFound.exception';
4import { User } from '@prisma/client';
5 
6@Injectable()
7export class UsersService {
8  constructor(private readonly prismaService: PrismaService) {}
9 
10  async getByEmail(email: string) {
11    const user: User | null = await this.prismaService.user.findUnique({
12      where: {
13        email,
14      },
15    });
16    if (!user) {
17      throw new UserNotFoundException();
18    }
19 
20    return user;
21  }
22 
23  // ...
24}

To use Prisma with the class-transformer library, we need to create a separate class.

userResponse.dto.ts
1import { User } from '@prisma/client';
2import { Exclude } from 'class-transformer';
3 
4export class UserResponseDto implements User {
5  id: number;
6  email: string;
7  name: string;
8  addressId: number;
9 
10  @Exclude()
11  password: string;
12}

Transforming the data

The most crucial thing to understand is that Prisma does not return the UserResponseDto class when we query the database. The most straightforward way of transforming our data into the UserResponseDto is to use the plainToInstance function provided by the class-transformer library.

authentication.controller.ts
1import {
2  Req,
3  Controller,
4  UseGuards,
5  Get,
6  UseInterceptors,
7  ClassSerializerInterceptor,
8} from '@nestjs/common';
9import RequestWithUser from './requestWithUser.interface';
10import JwtAuthenticationGuard from './jwt-authentication.guard';
11import { UserResponseDto } from '../users/dto/userResponseDto';
12import { plainToInstance } from 'class-transformer';
13 
14@Controller('authentication')
15@UseInterceptors(ClassSerializerInterceptor)
16export class AuthenticationController {
17  @UseGuards(JwtAuthenticationGuard)
18  @Get()
19  authenticate(@Req() request: RequestWithUser) {
20    return plainToInstance(UserResponseDto, request.user);
21  }
22 
23  // ...
24}

With the above approach, we create instances of the UserResponseDto that uses the @Exclude() decorator. The ClassSerializerInterceptor can understand this data and strip the password before the response reaches the user.

Mapping the response with an interceptor

Having to manually use the plainToInstance function every time we want to take advantage of the ClassSerializerInterceptor is not ideal and prone to mistakes. An alternative is creating a custom interceptor following the official documentation.

transformData.interceptor.ts
1import {
2  CallHandler,
3  ExecutionContext,
4  Injectable,
5  NestInterceptor,
6} from '@nestjs/common';
7import { map } from 'rxjs';
8import { ClassConstructor, plainToInstance } from 'class-transformer';
9 
10@Injectable()
11export class TransformDataInterceptor implements NestInterceptor {
12  constructor(private readonly classToUse: ClassConstructor<unknown>) {}
13 
14  intercept(context: ExecutionContext, next: CallHandler) {
15    return next.handle().pipe(
16      map((data) => {
17        return plainToInstance(this.classToUse, data);
18      }),
19    );
20  }
21}

Above, we modify the controller’s response by converting it to a class instance provided as an argument. A significant advantage of the custom interceptor is that it is straightforward to use.

authentication.controller.ts
1import {
2  Req,
3  Controller,
4  UseGuards,
5  Get,
6  UseInterceptors,
7  ClassSerializerInterceptor,
8} from '@nestjs/common';
9import RequestWithUser from './requestWithUser.interface';
10import JwtAuthenticationGuard from './jwt-authentication.guard';
11import { UserResponseDto } from '../users/dto/userResponseDto';
12import { TransformDataInterceptor } from '../utils/transformData.interceptor';
13 
14@Controller('authentication')
15@UseInterceptors(ClassSerializerInterceptor)
16export class AuthenticationController {
17  @UseGuards(JwtAuthenticationGuard)
18  @UseInterceptors(new TransformDataInterceptor(UserResponseDto))
19  @Get()
20  authenticate(@Req() request: RequestWithUser) {
21    return request.user;
22  }
23 
24  // ...
25}

Furthermore, suppose all methods in our controller return the same data type. In that case, we can use @UseInterceptors(new TransformDataInterceptor(UserResponseDto)) on the whole controller instead of doing that separately for each method. This is especially useful because the plainToInstance function works with arrays out of the box. Therefore, we can use our custom interceptor when a method in our controller returns an array.

Summary

In this article, we’ve taken a look at how to serialize responses with NestJS and used an example of removing a field we don’t want to expose. To understand how it works, we first investigated how serializing works when using TypeORM. Doing that helped us find the missing step we need to perform when serializing the responses in a project that uses Prisma.

Since remembering to use the plainToInstance function manually can be quite a chore, we created the TransformDataInterceptor to do it for us. Since it works fine with arrays, it covers a wide variety of use cases. Thanks to doing all of the above, we can serialize our data using various decorators from the class-transformer library.