Edit:
I have looked at this question/answer How to exclude entity field from controller json
But, as per below - this is excluding that field from all queries (to the porint where when trying to process user validation, the password field is excluded using the findOne repository query on a route/controller method that does not have ClassSerializerInterceptor
I have an entity within nest.js / typeorm; I am trying to exclude the password field from the returned json, but not exclude the password field from any repository queries within my service. For example:
user.entity.ts
:
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn,
UpdateDateColumn, ManyToOne } from 'typeorm';
import { Exclude } from 'class-transformer';
import { Account } from '../accounts/account.entity';
@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
firstName: string;
@Column()
lastName: string;
@Column({
unique: true,
})
email: string;
@Column()
password: string;
}
auth.controller.ts
:
import { Controller, Post, Body, Request, Req, Get, UseInterceptors, ClassSerializerInterceptor, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { IUserRequest } from '../../interfaces/user-request.interface';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('/login')
async login(@Request() req: Request) {
const user = await this.authService.checkCredentials(req.body);
return this.authService.logUserIn(user.id);
}
@Get('/profile')
@UseGuards(AuthGuard())
@UseInterceptors(ClassSerializerInterceptor)
async profile(@Request() req: IUserRequest) {
const profile = await this.authService.getLoggedInProfile(req.user.id);
return { profile };
}
}
If I add Exclude()
to password like so
@Exclude()
@Column()
password: string;
the password is included in the response
If I remove the Column()
from password,
@Exclude()
password: string;
Password is excluded from response and all internal queries such as:
const user = await this.userRepository.findOne({ where: { id }, relations: ['account']});
Is this possible in nest.js using the ClassSerializerInterceptor
?
If so, would appreciate a pointer in the right direction.
You can skip properties depending on the operation. In your case, you would use:
@Column()
@Exclude({ toPlainOnly: true })
password: string;
This means, that password is only skipped when a class is transformed to json (when you send a response) and not when json is transformed to a class (when you get a request).
Then add the @UseInterceptors(ClassSerializerInterceptor)
to your controller or a controller method. This will automatically transform an entity class to json, when you return it.
For the ClassSerializerInterceptor
to work, make sure that your entity was transformed to a class first. This can be automatically done by using the ValidationPipe
with the { transform: true}
option or by returning an entity from a repository (database). Also, you have to return the entity itself:
@Post()
@UseInterceptors(ClassSerializerInterceptor)
addUser(@Body(new ValidationPipe({transform: true})) user: User) {
// Logs user with password
console.log(user);
// Returns user as JSON without password
return user;
}
Otherwise, you have to transform it manually:
async profile(@Request() req: IUserRequest) {
// Profile comes from the database so it will be an entity class instance already
const profile = await this.authService.getLoggedInProfile(req.user.id);
// Since we are not returning the entity directly, we have to transform it manually
return { profile: plainToClass(profile) };
}