Created
October 17, 2019 10:10
-
-
Save ahmadarif/b3686803f80d0c0d51262783d368d7da to your computer and use it in GitHub Desktop.
Form Validation
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 { ArgumentMetadata, HttpException, Injectable, PipeTransform } from '@nestjs/common'; | |
import { plainToClass } from 'class-transformer'; | |
import { validate, ValidationError } from 'class-validator'; | |
@Injectable() | |
export class ValidationPipe implements PipeTransform<any> { | |
async transform(value: any, { metatype }: ArgumentMetadata) { | |
if (!metatype || !this.toValidate(metatype)) { | |
return value; | |
} | |
const object = plainToClass(metatype, value); | |
let errors: ValidationError[]; | |
try { | |
errors = await validate(object); | |
} catch (e) { | |
return value; | |
} | |
const errorBody: ErrorBody[] = []; | |
// tslint:disable-next-line:prefer-for-of | |
for (let i = 0; i < errors.length; i++) { | |
const body = new ErrorBody(); | |
body.property = errors[i].property; | |
body.messages = []; | |
// tslint:disable-next-line:forin | |
for (const key in errors[i].constraints) { | |
body.messages.push(errors[i].constraints[key]); | |
} | |
errorBody.push(body); | |
} | |
if (errors.length > 0) { | |
throw new HttpException({ message: 'Validation failed', errors: errorBody }, 400); | |
} | |
return value; | |
} | |
private toValidate(metatype: any): boolean { | |
const types: any[] = [String, Boolean, Number, Array, Object]; | |
return !types.includes(metatype); | |
} | |
} | |
// tslint:disable-next-line:max-classes-per-file | |
class ErrorBody { | |
property: string; | |
messages: string[]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment