nestjs 中的元类型是什么? [英] What is a metatype in nestjs?

查看:89
本文介绍了nestjs 中的元类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读nestjs 官方文档,我遇到了ValidationPipe 的以下实现:

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

我不明白 transform 方法中的逻辑.如果有人能逐行解释这件作品,那就太好了.我认为问题源于我不太明白 ArgumentMetadata 是什么以及它来自哪里.

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.

推荐答案

Metatype 是传递到管道中的对象的类类型,通过反射和一些魔法检索但是如果 你想要 看看这里 代码.

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.

本质上,如果您有 @Body() body: MyCustomClass 那么元类型将等于 MyCustomClass.这对于 plainToClass 方法是必需的,因此它知道将 JSON 序列化为哪个类.如果您正在使用 JavaScript 或不提供类型,则元类型将是未定义的

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

这篇关于nestjs 中的元类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆