Nestjs 序列化(Serialization)
NestJs仿小米商城项目实战视频教程(视频+课件+源码): https://www.itying.com/goods-1139.html
在发送实际响应之前,Serializers为数据操作提供了干净的抽象层。例如,应始终从最终响应中排除敏感数据(如用户密码) λ yarn add class-transformer
cats.entity.ts
import { PrimaryGeneratedColumn, Column, Entity } from 'typeorm'; import { Exclude, Expose } from 'class-transformer'; @Entity() export class Cats { @PrimaryGeneratedColumn() id: number; @Column({ length: 45 }) name: string; @Exclude() // 排除掉该字段 @Column('int') age: number; @Expose() get hello(): string { return `hello ${this.name}.`; // 暴露出一个计算属性 } constructor(partial: Partial<Cats>) { Object.assign(this, partial); } }
在控制器返回时做处理
import { Cats } from './cats.entity'; @UseInterceptors(ClassSerializerInterceptor) # @Get('cats') async findAll(): Promise<Cats[]> { // [{id, name, age}] => [{id, name}] return (await this.catsService.find()).map(el => new Cats(el)) # }