我在我的代码中使用了DTO,并且得到了预期的响应,但是在代码中DTO并未抛出错误,例如
export class CreateCatDto {
readonly name: string;
readonly age: number;
readonly breed: string;
}
用这个名字,年龄,品种是必填字段,每个都有其数据类型,但是当我在邮递员上运行时,如果我没有将所有必填字段或仅一个字段传递到邮递员体内,我不会收到像年龄这样的错误如果我已经传递了其他两个字段,或者我没有根据数据类型给出参数值,则是必需的:-age:25,那么它也应该引发错误,但我没有得到。
所以,这是为]创建的类>
import { ApiProperty } from '@nestjs/swagger';
export class Cat {
@ApiProperty({ example: 'Kitty', description: 'The name of the Cat' })
name: string;
@ApiProperty({ example: 1, description: 'The age of the Cat' })
age: number;
@ApiProperty({
example: 'Maine Coon',
description: 'The breed of the Cat',
})
breed: string;
}
这是我要在其中导入类和Dto的控制器。
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { CatsService } from './cats.service';
import { Cat } from './classes/cat.class';
import { CreateCatDto } from './dto/create-cat.dto';
@ApiBearerAuth()
@ApiTags('cats')
@Controller('cats')
export class CatsController {
constructor(private readonly catsService: CatsService) {}
@Post()
@ApiOperation({ summary: 'Create cat' })
@ApiResponse({ status: 403, description: 'Forbidden.' })
async create(@Body() createCatDto: CreateCatDto): Promise<Cat> {
return this.catsService.create(createCatDto);
}
}
我在代码中使用DTO,并且按预期方式获得响应,但是在代码中DTO不会抛出错误,例如,导出类CreateCatDto {只读名称:字符串;只读年龄:...
我不知道为什么选择了nestjs-swagger标记,DTO本身不会验证输入,也许您需要根据文档https://docs.nestjs.com/techniques/validation#validation的建议将ValidationPipe与class-validator包一起使用
就像现在在代码上放置装饰符一样简单: