如何验证 DTO 字段?

How to validate a DTO fields?

我有一个没有入口参数的端点:

async myendpoint(): Promise<any> {
   const customer = await this.customerService.findOne(1);
   if (customer) {
      return await this.customerService.mapToDestination(customer);
   }...
}

然后我有我的方法 mapToDestination,我只需分配 vars:

async mapToDestination(customer: Customer): Promise<DestinationDto> {
    const destination: DestinationDto = {
          lastname: customer.lastname,
          firstname: customer.firstname,...

终于有了我的 DTO:

import {IsEmail, IsNotEmpty, IsOptional, IsNumber, IsBoolean, IsString, IsDate, MaxLength, Length, NotEquals} from 'class-validator';
import {ApiProperty} from '@nestjs/swagger';

export class DestinationDto {


  @IsString()
  @IsNotEmpty()
  @MaxLength(32)
  lastname: string;

  @IsString()
  @IsNotEmpty()
  @MaxLength(20)
  firstname: string; ...

当我在 mapToDestination() 方法中映射时,我希望我的 DTO 字段在装饰器之后自动得到验证。我浏览了网络和官方文档,并尝试了验证器(ValidationPipe),但它似乎不是我需要的,因为它验证了端点条目参数。

请你解释一下如何实现这种自动验证?提前致谢。

我不会“自动”,但您可以从 class 验证器实例化您自己的验证器实例,并将其用于您服务中的 DTO。否则,它永远不会自动发生,因为正如您所说,ValidationPipe 仅适用于端点的入口。

例子

mapToDestination 内只要 customer is an instance of DestinationDTO` 你就可以有这样的东西:

@Injectable()
export class CustomerService {

  async mapToDestination(customer: DestinationDTO) {
    const errors = await validate(customer);
    if (errors) {
      throw new BadRequestException('Some Error Message');
    }
    ...
  }
  
  ...
}