igor
igor

Reputation: 147

What is a metatype in nestjs?

Reading the official nestjs doc, I've come across the following implementation of ValidationPipe:

import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
  async transform(value: any, { metatype }: ArgumentMetadata) {
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length > 0) {
      throw new BadRequestException('Validation failed');
    }
    return value;
  }

  private toValidate(metatype: Function): boolean {
    const types: Function[] = [String, Boolean, Number, Array, Object];
    return !types.includes(metatype);
  }
}

I don't understand the logic put in the transform method. It would be great if someone would explain this piece line by line. I think the problem steams from the fact that I don't quite understand what ArgumentMetadata is and where it comes from.

Upvotes: 0

Views: 1600

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70432

Metatype is the class type of the object being passed into the pipe, retrieved via reflection and some magic but if you wanna look here's the code.

Essentially, if you have @Body() body: MyCustomClass then metatype will be equal to MyCustomClass. This is necessary for the plainToClass method so it knows what class it is serializing the JSON into. If you are working with JavaScript or don't provide a type, then metatype will be undefined

Upvotes: 5

Related Questions