小编ush*_*her的帖子

Nestjs 响应序列化与对象数组

我想通过 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;  
}
Run Code Online (Sandbox Code Playgroud)

用户响应类

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, …
Run Code Online (Sandbox Code Playgroud)

serialization node.js typescript nestjs class-transformer

7
推荐指数
1
解决办法
2万
查看次数