【问题标题】:How to validate the direct function call in nestjs?如何验证nestjs中的直接函数调用?
【发布时间】:2022-01-08 14:06:24
【问题描述】:

我正在尝试发送直接函数调用,并设置了 DTO,但不起作用。 这是我控制器中的代码(发送是我的 DTO):

 @Post('/Send')
  async SendE(body: Send) {
    const mail = await this.messageProducer.SendMessage(body);
    return mail;
  }

我在这里直接调用 SendE 函数:

  @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);
  }

我希望“发送”DTO 可以验证“toJson”,但它不起作用。 这是我的 DTO 的样子:

export class Send{
  @IsString()
  @ApiProperty({ required: true })
  MessageID: string;
  }

这是 toJson 的样子:

{
  MessageID: 123
}

如果我发送一个非字符串 MessageID,它可以通过 DTO。 请帮忙

【问题讨论】:

    标签: javascript node.js validation apache-kafka nestjs


    【解决方案1】:

    您必须启用validationPipe 才能启用DTO,根据docs of NestJS 有两种方法。 ValidationPipe 是从 @nestjs/common 导出的。

    1。全球在您的main.ts

    // validate incoming requests
    app.useGlobalPipes(
      new ValidationPipe({
        transform: true,
      })
    );
    

    2。每个控制器

    @Post()
    @UsePipes(new ValidationPipe({ transform: true }))
    async create(@Body() createCatDto: CreateCatDto) {
      this.catsService.create(createCatDto);
    }
    

    【讨论】:

    • 您好,我是直接在应用程序中调用 SendE,而不是从 API。如果我使用邮递员发送发布请求,则 dto 将起作用。但是,如果我直接在应用程序中调用该函数,即使我启用了validationPipe,dto 也将不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 2014-09-08
    • 2021-08-10
    • 1970-01-01
    • 2019-11-01
    • 2020-12-05
    相关资源
    最近更新 更多