演示代码:
1. logs.controller.ts
import { Body, Controller, Post, UseInterceptors } from '@nestjs/common';
import { IsNotEmpty, IsString } from 'class-validator';
import { SerializeInterceptor } from '../interceptors/serialize/serialize.interceptor';
import { Expose } from 'class-transformer';
class LogsDto {
@IsString()
@IsNotEmpty()
msg: string;
@IsString()
id: string;
@IsString()
name: string;
}
class PublicLogsDto {
@Expose()
msg: string;
}
@Controller('logs')
export class LogsController {
@Post()
@UseInterceptors(new SerializeInterceptor(PublicLogsDto))
postTest(@Body() dto: LogsDto) {
console.log('🚀 ~ LogsController ~ postTest ~ dto:', dto);
return dto;
}
}
2. serialize.interceptor.ts代码
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { map, Observable } from 'rxjs';
@Injectable()
export class SerializeInterceptor implements NestInterceptor {
constructor(private dto: any) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
// const req = context.switchToHttp().getRequest();
console.log('这里在拦截器执行之前');
return next.handle().pipe(
map((data) => {
console.log('datadata', data);
return plainToInstance(this.dto, data, {
// 设置为true之后,所有经过该interceptor的接口都需要设置Expose或Exclude
// Expose就是设置哪些字段需要暴露,Exclude就是设置哪些字段不需要暴露
excludeExtraneousValues: true,
});
}),
);
}
}