【问题标题】:ValidationPipes doesnt work with Body specific typeValidationPipe 不适用于 Body 特定类型
【发布时间】:2021-06-05 00:14:21
【问题描述】:

我有一个简单的问题。我正在尝试将ValidationPipe 应用于我的一个端点,即 POST 此端点的职责很简单 - 添加发票,但在此之前我想验证正文。

所以我这样做了:

invoice.dto.ts

import { ContractorDto } from './contractor.dto';
import { IncomeDto } from './income.dto';
import { ExpensesDto } from './expenses.dto';
import {
    IdValidator,
    PositionValidator,
    DateOfEventValidator,
    DescriptionValidator,
    RegistryValidator,
    ContractorValidator,
    IncomeValidator,
    ExpensesValidator,
} from '../helpers/invoiceValidation.decorator';

export class InvoiceDto {
    @IdValidator() id: string;
    @PositionValidator() position: number;
    @DateOfEventValidator() dateOfEvent: string;
    @RegistryValidator() registry: string;
    @DescriptionValidator() description: string;
    @ContractorValidator() contractor: ContractorDto;
    @IncomeValidator() income: IncomeDto;
    @ExpensesValidator() expenses: ExpensesDto;
}

invoices.controller.ts

type XYZ = Omit<InvoiceDto, 'id'>;

@Post('/add')
addInvoice(
    @Res() res: Response,
    @Body(
        new ValidationPipe({
            transform: true,
            disableErrorMessages: false,
            always: true,
            stopAtFirstError: true,
            validateCustomDecorators: true,
            skipMissingProperties: false,
        })
    )
    body: XYZ, // here is a problem, when I'm using InvoiceDto - validation works, but when i try to use Omit it doesnt work
) {
    // I dont neet to validate ID field because I will generate it on backend
    const invoice = this.invoicesService.addInvoice(body);
    return res.json(invoice);
}

invoiceValidation.decorator.ts

export function IdValidator() {
    return applyDecorators(
        IsDefined({ message: 'ID of an inovice is required!' }),
        IsString({ message: 'ID must be a string!' }),
        Length(21, 21, { message: 'ID is not valid!' }),
    );
}

export function PositionValidator() {
    return applyDecorators(
        IsDefined({ message: 'Position of invoice is required!' }),
        IsNotEmpty(),
        IsInt({ message: 'Position of invoice must be a number' }),
        Min(1, { message: 'Position of invoice must be greater than 0' }),
    );
}

export function DateOfEventValidator() {
    return applyDecorators(
        IsDefined({ message: 'Date of invoice event is required!' }),
        IsOnlyDate(),
    );
}

  // I've just add a couple of validators

GIST backup here

我认为问题在于当我尝试在正文类型上使用 Omit&lt;SCHEMA, OMIT_VALUE&gt; 时,我觉得我的验证器忽略了我的“忽略正文类型”并传递所有数据。 我将不胜感激任何帮助或建议

【问题讨论】:

标签: typescript pipe nestjs class-validator


【解决方案1】:

如果您使用的是Omit&lt;T&gt; 泛型,则由于 Typescript 无法反映泛型类型,因此它将无法工作。你可以利用@nestjs/mapperd-typesOmitType() mixin 为你创建一个新的类。

export class OmitSchema extends OmitType(SchemaClass, ['fields', 'to', 'emit'] as const) {}

【讨论】:

  • 不错!谢谢你,我已经这样做了。但是仍然不明白为什么它不能与 TypeScript Omit 一起使用?这是什么意思 - “ts 不能反映泛型类型”?
  • Nest 使用所谓的反射来获取有关正在处理的路线的信息。路由的参数类型,应该运行的守卫,管道等。泛型是接受额外类型参数(或更多)的通用类型,例如Omit&lt;T, string&gt;。由于Omit 首先不是一个类,因此打字稿很难反映这一点,即使它使用泛型类类型作为第一个参数,打字稿也不能反映该信息,因此 Nest 不能使用它.这就是为什么 Nest 创建了@nestjs/mapped-types 来处理这种情况
猜你喜欢
  • 1970-01-01
  • 2013-04-08
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2022-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多