简体   繁体   English

Nest JS 使用全局管道验证来自外部 API 的数据

[英]Nest JS validate data from an external API using global pipes

I am developing a Nestjs project.我正在开发一个 Nestjs 项目。 Here I am fetching the data from another rest API. I fetch the data from the API and store it in my database.在这里,我从另一个 rest API 获取数据。我从 API 获取数据并将其存储在我的数据库中。 However, I need to validate the data from the API that I got.但是,我需要验证我得到的 API 中的数据。 How can I do this using class-validator ?我如何使用class-validator来做到这一点?

I used global pipe in main.ts file like -我在 main.ts 文件中使用了全局 pipe,例如 -

app.useGlobalPipes(
   new ValidationPipe({
      transform: true,
      whitelist: true,
   }),
);

I have created my DTO properly.我已经正确地创建了我的 DTO。 An example DTO like the one I have created is -像我创建的 DTO 示例是 -

export class DataDTO {
  @IsString()
  name: string;

  @IsInt()
  @Min(0)
  @Max(100)
  age: number;
}

My controller code is as below -我的 controller 代码如下 -

  @Get()
  async getData() {
    const data: DataDTO = await fetchDataFromExternalAPI();
  }

I got any data as the data value.我得到任何数据作为data值。 No exception or error occurs here.这里没有异常或错误发生。 Need some help from the experts.需要专家的一些帮助。

Pipes only work on requests to your server.管道仅适用于您的服务器的请求。 If you want to validate data that you retrieve from an external source, you can still use a DTO as you are, but you need to make use of class-transformer 's plainToInstance to take the data and create an instance of the DTO and then use class-validator 's validate to check that the instance matches what you are expecting.如果您想验证从外部源检索的数据,您仍然可以像现在这样使用DTO ,但是您需要使用class-transformerplainToInstance来获取数据并创建 DTO 的实例,然后使用class-validatorvalidate来检查实例是否符合您的预期。

@Get()
async getData() {
  cosnt data: DataDto = await fetchDataFromExternalAPI();
  const dataInstance = plainToInstance(DataDto, data);
  const validated = validate(dataInstance)
  if (validated.errors.length) {
    throw mapErrorsToErrorObject(validated.errors)
  }
  return doTheRestOfLogic(dataInstance);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM