rony
rony

Reputation: 520

How to serialize Prisma Object in NestJS?

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

Upvotes: 2

Views: 5248

Answers (3)

IBRAHIM ALI MUSAH
IBRAHIM ALI MUSAH

Reputation: 979

it's easy to create a function that you can use to exclude certain fields in a type-safe way.

Excluding the Password Field

The following is a type-safe exclude function returns a user without the password field.

// Exclude keys from user
function exclude<User, Key extends keyof User>(
  user: User,
  keys: Key[]
): Omit<User, Key> {
  for (let key of keys) {
    delete user[key]
  }
  return user
}

function main() {
  const user = await prisma.user.findUnique({ where: 1 })
  const userWithoutPassword = exclude(user, ['password'])
}

Upvotes: 0

pakut2
pakut2

Reputation: 672

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

Upvotes: 2

Felipe D. S. Lima
Felipe D. S. Lima

Reputation: 21

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;
}

Upvotes: 2

Related Questions