Serializing the response with Prisma
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…
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 import { Column, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn, } from 'typeorm'; import { Exclude } from 'class-transformer'; import Address from './address.entity'; @Entity() class User { @PrimaryGeneratedColumn() public id: number; @Column({ unique: true }) public email: string; @Column() public name: string; @OneToOne(() => Address, { eager: true, cascade: true, }) @JoinColumn() public address: Address; @Column() @Exclude() public password: string; } export default User;Thanks to the above, when we query the database using TypeORM, it returns instances of the User class defined above.const user = await this.usersRepository.findOneBy({ email }); console.log(user instanceof User); // trueWhen we return instances of our User class through the controller, we can use the ClassSerializerInterceptor built into NestJS. user.controller.ts import { Req, Controller, UseGuards, Get, ClassSerializerInterceptor, UseInterceptors, } from '@nestjs/common'; import RequestWithUser from './requestWithUser.interface'; import JwtAuthenticationGuard from './jwt-authentication.guard'; @Controller('authentication') @UseInterceptors(ClassSerializerInterceptor) export class AuthenticationController { @UseGuards(JwtAuthenticationGuard) @Get() authenticate(@Req() request: RequestWithUser) { return request.user; } // ... } 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 model User { id Int @id @default(autoincrement()) email String @unique name String password String address Address? @relation(fields: [addressId], references: [id]) addressId Int? @unique posts Post[] }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 import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { UserNotFoundException } from './exceptions/userNotFound.exception'; import { User } from '@prisma/client'; @Injectable() export class UsersService { constructor(private readonly prismaService: PrismaService) {} async getByEmail(email: string) { const user: User | null = await this.prismaService.user.findUnique({ where: { email, }, }); if (!user) { throw new UserNotFoundException(); } return user; } // ... }To use Prisma with the class-transformer library, we need to create a separate class. userResponse.dto.ts import { User } from '@prisma/client'; import { Exclude } from 'class-transformer'; export class UserResponseDto implements User { id: number; email: string; name: string; addressId: number; @Exclude() password: string; } 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 import { Req, Controller, UseGuards, Get, UseInterceptors, ClassSerializerInterceptor, } from '@nestjs/common'; import RequestWithUser from './requestWithUser.interface'; import JwtAuthenticationGuard from './jwt-authentication.guard'; import { UserResponseDto } from '../users/dto/userResponseDto'; import { plainToInstance } from 'class-transformer'; @Controller('authentication') @UseInterceptors(ClassSerializerInterceptor) export class AuthenticationController { @UseGuards(JwtAuthenticationGuard) @Get() authenticate(@Req() request: RequestWithUser) { return plainToInstance(UserResponseDto, request.user); } // ... }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 import { CallHandler, ExecutionContext, Injectable, NestInterceptor, } from '@nestjs/common'; import { map } from 'rxjs'; import { ClassConstructor, plainToInstance } from 'class-transformer'; @Injectable() export class TransformDataInterceptor implements NestInterceptor { constructor(private readonly classToUse: ClassConstructor