Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude entity field from returned by controller JSON. NestJS + Typeorm

I want to exclude password field from returned JSON. I am using NestJS and Typeorm.

The solution provided on this question doesn't work for me or in NestJS. I can post my code if needed. Any other ideas or solutions? Thanks.

like image 498
Vladyslav Moisieienkov Avatar asked May 15 '18 22:05

Vladyslav Moisieienkov


2 Answers

I'd suggest creating an interceptor that takes advantage of the class-transformer library:

@Injectable() export class TransformInterceptor implements NestInterceptor {   intercept(     context: ExecutionContext,     call$: Observable<any>,   ): Observable<any> {     return call$.pipe(map(data => classToPlain(data)));   } } 

Then, simply exclude properties using @Exclude() decorator, for example:

import { Exclude } from 'class-transformer';  export class User {     id: number;     email: string;      @Exclude()     password: string; } 
like image 161
Kamil Myśliwiec Avatar answered Sep 19 '22 23:09

Kamil Myśliwiec


You can overwrite the toJSON method of the model like this.

@Entity() export class User extends BaseAbstractEntity implements IUser {   static passwordMinLength: number = 7;    @ApiModelProperty({ example: faker.internet.email() })   @IsEmail()   @Column({ unique: true })   email: string;    @IsOptional()   @IsString()   @MinLength(User.passwordMinLength)   @Exclude({ toPlainOnly: true })   @Column({ select: false })   password: string;    @IsOptional()   @IsString()   @Exclude({ toPlainOnly: true })   @Column({ select: false })   passwordSalt: string;    toJSON() {     return classToPlain(this);   }    validatePassword(password: string) {     if (!this.password || !this.passwordSalt) {       return false;     }     return comparedToHashed(password, this.password, this.passwordSalt);   } } 

By using the class-transformer method of plainToClass along with the @Exclude({ toPlainOnly: true }), the password will be excluded from the JSON response, but will be available in the model instance. I like this solution because it keeps all the model configuration in the entity.

like image 36
Francisco Javier Sucre Gonzále Avatar answered Sep 20 '22 23:09

Francisco Javier Sucre Gonzále