Skip to content

Instantly share code, notes, and snippets.

@bjyoungblood
Created January 18, 2018 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjyoungblood/dffe8478696eb10ffd0e477693a023f5 to your computer and use it in GitHub Desktop.
Save bjyoungblood/dffe8478696eb10ffd0e477693a023f5 to your computer and use it in GitHub Desktop.
import { Pipe, PipeTransform, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
function isNil(obj: any): boolean {
return typeof obj === 'undefined' || obj === null;
}
@Pipe()
export class ValidationPipe<T, V> implements PipeTransform<any> {
public async transform(value: V, metadata: ArgumentMetadata): Promise<T> {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
throw new Error('Unable to validate type');
}
// this rates in the top 10 most annoying bugs I've ever had to debug
if (typeof value === 'object' && !(value instanceof Object)) {
value = Object.assign({}, value);
}
const entity = plainToClass<T, V>(metatype, value);
const errors = await validate(entity);
if (errors.length > 0) {
throw new BadRequestException(errors);
}
return entity;
}
private toValidate(metatype: any): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find((type) => metatype === type) && !isNil(metatype);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment