Search code examples
validationnestjsclass-validator

Nest JS validate data from an external API using global pipes


I am developing a Nestjs project. Here I am fetching the data from another rest API. I fetch the data from the API and store it in my database. However, I need to validate the data from the API that I got. How can I do this using class-validator?

I used global pipe in main.ts file like -

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

I have created my DTO properly. An example DTO like the one I have created is -

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

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

My controller code is as below -

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

I got any data as the data value. No exception or error occurs here. Need some help from the experts.


Solution

  • 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.

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