在整合swagger中,雖然入?yún)㈦m然使用了dto,但是我們使用instanceof發(fā)現(xiàn)它并不是我們dto的instance
image.png
如果想要達到dto校驗的效果需要自己配置兜材,這里不同的配置會有不同的效果,這里最終的效果是這樣的:前端傳入的字段必須在dto中存在据沈,如果不存在就會被忽略掉,如果字段存在但是類型不一樣則會報錯,嵌套dto和數(shù)組的配置有些特殊需要注意.
1.首先安裝校驗工具包
npm i --save class-validator class-transformer
2.在入?yún)equest dto上加上對應的裝飾器
import { ApiProperty } from "@nestjs/swagger"
import { Type } from "class-transformer"
import { IsNumber, IsOptional, IsString, ValidateNested } from "class-validator"
export class UserHobby{
@ApiProperty()
//數(shù)組的配置要加上each:true
@IsString({each:true})
hobbyName:string[]
}
export class UserRequestDto{
//如果該字段前端可能傳入戒悠,也可能不傳入則使用@IsOptional()
@IsOptional()
@IsString()
@ApiProperty()
name:string
@IsNumber()
@ApiProperty()
age:number
//如果是嵌套類型是數(shù)組可以在ValidateNested配置each:true
//@Type 指定嵌套類型
@ValidateNested()
@Type(() => UserHobby)
@ApiProperty()
hobbyName:UserHobby
}
3.在main.ts配置全局使用validate該功能
app.useGlobalPipes
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter()
);
const options = new DocumentBuilder()
.setTitle('nest-demo')
.setDescription('The nest-demo API description')
.setVersion('1.0')
.addTag('nest-demo')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
//全局使用dto校驗
app.useGlobalPipes(
new ValidationPipe({
whitelist:true,
transform:true
})
);
await app.listen(3000, '0.0.0.0');
console.warn(`app start listen on 3000`)
}
bootstrap();
whitelist:true, 作用是將傳入的參數(shù)只保留使用裝飾器的字段(類似@IsNumber())
transform:true 作用是將參數(shù)轉為對應的class 的instance.
最終效果:
image.png
tips1:如果該字段前端可能傳入轧膘,也可能不傳入則使用@IsOptional()
tips2:開啟此功能將會損耗很少一部分性能
tips3: plainToInstance from 'class-transformer 此方法可以將對象轉為dto