How to serialize Prisma Object in NestJS?

Viewed 1214

I have tried using Class Transformer, but it doesn't make any sense since Prisma doesn't need Entity, and Prisma Type cannot be Exclude() Is there any way to exclude key from Prisma object e.g. createdAt or password? Thank you

2 Answers

I did it this way

In file: user.entity.ts

import { Role, User as UserPrisma } from '@prisma/client';
import { Exclude } from 'class-transformer';

export class User implements UserPrisma {
  id: string;
  name: string;
  email: string;

  @Exclude()
  password: string;

  @Exclude()
  role: Role;

  createdAt: Date;
  updatedAt: Date;
}

There are few options

  • select specific fields (not ideal, lots of duplication and leaves room for error)
  • add user.password = undefined before returning (not very clean, also room for error)
  • create entity mirroring prisma schema and use class-transformer (imo this misses the point of using prisma in general. In this situation you might as well use TypeORM or Sequelize to avoid duplication and multiple sources of truth)
  • create custom interceptor (imo the best solution atm)

Interceptor example:

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { map, Observable } from 'rxjs';

@Injectable()
export class RemovePasswordInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((value) => {
        value.password = undefined;
        return value;
      }),
    );
  }
}

This issue is being discussed atm, so I suggest looking into this thread

Related