Skip to content

Instantly share code, notes, and snippets.

@dexfs
Created February 26, 2024 23:02
Show Gist options
  • Save dexfs/d056d7380a6637892ed89f50b8e0a9cb to your computer and use it in GitHub Desktop.
Save dexfs/d056d7380a6637892ed89f50b8e0a9cb to your computer and use it in GitHub Desktop.
import {
ArgumentMetadata,
BadRequestException,
PipeTransform,
ValidationPipe,
} from '@nestjs/common';
import { Product1, Product2 } from './dtos/create-product.dto';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
/** @see https://stackoverflow.com/questions/54057006/nestjs-validating-body-conditionally-based-on-one-property **/
export class ProductValidationPipe implements PipeTransform {
async transform(value: any) {
if (!value) {
throw new BadRequestException('Invalid Request');
}
let dtoValidator: Product1 | Product2;
if (value.type === 'PRODUCT_1') {
dtoValidator = plainToInstance(Product1, value);
}
if (value.type === 'PRODUCT_2') {
dtoValidator = plainToInstance(Product2, value);
}
const errors = await validate(dtoValidator);
if (errors.length > 0) {
const validationPipe = new ValidationPipe();
const exceptionFactory = validationPipe.createExceptionFactory();
throw exceptionFactory(errors);
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment