I want ClassSerializerInterceptor
to make my response body match response type, currently it doesn't work and still returns all the fields that are returned from function.
Example of my response DTO:
export class SignedInUserDTO extends PartialType(
PickType(User, ['id', 'email', 'role']),
) {
@IsString()
accessToken: string;
}
For my DTO I also tried to attach @Exclude()
, but this had no effect.
Controller:
@Post('sign-in')
async signUp(@Body() signInUserDto: SignInUserDTO): Promise<SignedInUserDTO> {
return this.authService.signIn(signInUserDto);
}
How I set up interceptor in main.ts
:
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
I also tried to attach it directly to route like this:
@UseInterceptors(ClassSerializerInterceptor)
But neither method works. I really have no clue what is wrong here, any thoughts?
UPDATE:
I've played around for a few more hours, it's working with another route which just returns user from database, fields marked with @Exclude()
are not returned, which is correct, yet it still doesn't work for other routes, even using plainToInstance()
.
So this is happening because plain object is returned from response, but ClassSerializerInterceptor
can work only with classes.
I used approach like this: https://gist.github.com/ibayazit/dee57afc274297490e7265bcf4da63ab
And now for every route that returns plain object I attach @Serialize()
decorator.
Still I'd prefer to set this up on global level, any suggestions on that are higly appreciated.