Nestjs Response Serialization with array of objects
I would recommend to directly put the @Exclude
decorators on your entity class User
instead of duplicating the properties in UserResponse
. The following answer assumes you have done so.
Flat Response
If you have a look at the code of the ClassSerializerInterceptor
, you can see that it automatically handles arrays:
return isArray
? (response as PlainLiteralObject[]).map(item =>
this.transformToPlain(item, options),
)
: this.transformToPlain(response, options);
However, it will only transform them, if you directly return the array, so return users
instead of return {users: users}
:
@UseInterceptors(ClassSerializerInterceptor)
@Get('all')
async findAll(): Promise<User> {
return this.userService.findAll()
}
Nested Response
If you need the nested response, then your way is a good solution.
Alternatively, you can call class-transformer's serialize
directly instead of using the ClassSerializerInterceptor
. It also handles arrays automatically:
import { serialize } from 'class-transformer';
@Get('all')
async findAll(): Promise<UsersResponse> {
const users: User[] = await this.userService.findAll();
return {users: serialize(users)};
}