Reputation: 520
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
Reputation: 979
it's easy to create a function that you can use to exclude certain fields in a type-safe way.
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
Reputation: 672
There are few options
user.password = undefined
before returning (not very clean, also room for error)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
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