Skip to content
Snippets Groups Projects
Commit 08f59052 authored by L4168's avatar L4168
Browse files

forbidNonWhitelisted: true

parent 763d20b7
No related branches found
No related tags found
3 merge requests!59Development to master,!31Development,!29Json validation
import {
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException, HttpException, HttpStatus } from '@nestjs/common'; PipeTransform,
Injectable,
ArgumentMetadata,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { validate } from 'class-validator'; import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer'; import { plainToClass } from 'class-transformer';
@Injectable() @Injectable()
export class ValidationPipe implements PipeTransform<any> { export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) { async transform(value: any, metadata: ArgumentMetadata) {
if (value instanceof Object && this.isEmpty(value)) {
if (value instanceof Object && this.isEmpty(value)) { throw new HttpException(
throw new HttpException( 'Validation failed: No body submitted',
'Validation failed: No body submitted', HttpStatus.BAD_REQUEST HttpStatus.BAD_REQUEST,
); );
}
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
throw new HttpException(`Validation failed: ${this.formatErrors(errors)}`, HttpStatus.BAD_REQUEST);
}
return value;
} }
private toValidate(metatype: Function): boolean { const { metatype } = metadata;
const types: Function[] = [String, Boolean, Number, Array, Object]; if (!metatype || !this.toValidate(metatype)) {
return !types.includes(metatype); return value;
} }
const object = plainToClass(metatype, value);
private formatErrors(errors: any[]) { const errors = await validate(object, {
return errors.map(err => { whitelist: true,
for (let property in err.constraints) { forbidNonWhitelisted: true,
return err.constraints[property] });
} if (errors.length > 0) {
}).join(", "); throw new HttpException(
`Validation failed: ${this.formatErrors(errors)}`,
HttpStatus.BAD_REQUEST,
);
} }
return value;
}
private isEmpty(value: any) { private toValidate(metatype: Function): boolean {
return (Object.keys(value).length > 0) ? false : true; const types: Function[] = [String, Boolean, Number, Array, Object];
} return !types.includes(metatype);
} }
\ No newline at end of file
private formatErrors(errors: any[]) {
return errors
.map(err => {
for (let property in err.constraints) {
return err.constraints[property];
}
})
.join(', ');
}
private isEmpty(value: any) {
return Object.keys(value).length > 0 ? false : true;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment