[英]How to validate the direct function call in nestjs?
I am trying to send a direct function call, and I set the DTO, but not work.我正在尝试发送直接 function 调用,并且我设置了 DTO,但不起作用。 here is the code (Send is my DTO) in my controller:
这是我的 controller 中的代码(发送是我的 DTO):
@Post('/Send')
async SendE(body: Send) {
const mail = await this.messageProducer.SendMessage(body);
return mail;
}
I make a direct call to SendE function here:我在这里直接致电 SendE function:
@MessagePattern('Notification')
async readMessage(@Payload() message: any, @Ctx() context: KafkaContext) {
const messageString = JSON.stringify(context.getMessage().value);
const toJson = JSON.parse(messageString);
await this.SendE(toJson);
}
I want the "Send" DTO can validate the "toJson", but it does not work.我希望“发送”DTO 可以验证“toJson”,但它不起作用。 here is what my DTO looks like:
这是我的 DTO 的样子:
export class Send{
@IsString()
@ApiProperty({ required: true })
MessageID: string;
}
here is what the toJson looks like:这是 toJson 的样子:
{
MessageID: 123
}
If I send a non-string MessageID, it can pass the DTO.如果我发送一个非字符串 MessageID,它可以通过 DTO。 Please help
请帮忙
You have to enable validationPipe
to make DTO's, There are 2 approaches according to the docs of NestJS .您必须启用
validationPipe
才能制作 DTO,根据NestJS的文档有两种方法。 The ValidationPipe
is exported from @nestjs/common
. ValidationPipe
是从@nestjs/common
导出的。
main.ts
: main.ts
中:// validate incoming requests
app.useGlobalPipes(
new ValidationPipe({
transform: true,
})
);
@Post()
@UsePipes(new ValidationPipe({ transform: true }))
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.