Created
January 18, 2018 02:10
-
-
Save bjyoungblood/dffe8478696eb10ffd0e477693a023f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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