我想通过 nestjs 序列化技术序列化控制器响应。我没有找到任何方法,我的解决方案如下:
用户实体
export type UserRoleType = "admin" | "editor" | "ghost";
@Entity()
export class User {
@PrimaryGeneratedColumn() id: number;
@Column('text')
username: string;
@Column('text')
password: string;
@Column({
type: "enum",
enum: ["admin", "editor", "ghost"],
default: "ghost"
})
roles: UserRoleType;
@Column({ nullable: true })
profileId: number;
}
用户响应类
import { Exclude } from 'class-transformer';
export class UserResponse {
id: number;
username: string;
@Exclude()
roles: string;
@Exclude()
password: string;
@Exclude()
profileId: number;
constructor(partial: Partial<UserResponse>) {
Object.assign(this, partial);
}
}
import { Exclude, Type } from 'class-transformer';
import { User } from 'src/_entities/user.entity';
import { UserResponse } from './user.response';
export class UsersResponse {
@Type(() => UserResponse)
users: User[]
constructor() { }
}
控制器
@Controller('user')
export class UsersController {
constructor(
private readonly userService: UserService
) {
}
@UseInterceptors(ClassSerializerInterceptor)
@Get('all')
async findAll(
): Promise<UsersResponse> {
let users = await this.userService.findAll().catch(e => { throw new NotAcceptableException(e) })
let rsp =new UsersResponse()
rsp.users = users
return rsp
}
它有效,但我必须将数据库查询结果显式分配给响应用户成员。有没有更好的办法?非常感谢
这里是实际响应和想要的结果,以获得更好的解释。
这种方法的结果
{
"users": [
{
"id": 1,
"username": "a"
},
{
"id": 2,
"username": "bbbbbb"
}
]
}
想要的结果
{
{
"id": 1,
"username": "a"
},
{
"id": 2,
"username": "bbbbbb"
}
}