ValidationPipe 不适用于 Body 特定类型

ValidationPipes doesnt work with Body specific type

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

所以我这样做了:

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

我认为问题是当我尝试在 body 类型上使用 Omit<SCHEMA, OMIT_VALUE> 时,我觉得我的验证器忽略了我的 'omit type for body' 并传递了所有数据。 如果有任何帮助或建议,我将不胜感激

如果您使用的是 Omit<T> 泛型,由于 Typescript 无法反映泛型类型,因此无法使用。您可以使用 @nestjs/mapperd-typesOmitType() mixin 为您创建一个新的 class。

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