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 { PipeTransform, Injectable, ArgumentMetadata, BadRequestException, HttpException, HttpStatus } from '@nestjs/common';
import {
PipeTransform,
Injectable,
ArgumentMetadata,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) {
if (value instanceof Object && this.isEmpty(value)) {
throw new HttpException(
'Validation failed: No body submitted', 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;
async transform(value: any, metadata: ArgumentMetadata) {
if (value instanceof Object && this.isEmpty(value)) {
throw new HttpException(
'Validation failed: No body submitted',
HttpStatus.BAD_REQUEST,
);
}
private toValidate(metatype: Function): boolean {
const types: Function[] = [String, Boolean, Number, Array, Object];
return !types.includes(metatype);
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
private formatErrors(errors: any[]) {
return errors.map(err => {
for (let property in err.constraints) {
return err.constraints[property]
}
}).join(", ");
const object = plainToClass(metatype, value);
const errors = await validate(object, {
whitelist: true,
forbidNonWhitelisted: true,
});
if (errors.length > 0) {
throw new HttpException(
`Validation failed: ${this.formatErrors(errors)}`,
HttpStatus.BAD_REQUEST,
);
}
return value;
}
private isEmpty(value: any) {
return (Object.keys(value).length > 0) ? false : true;
}
}
\ No newline at end of file
private toValidate(metatype: Function): boolean {
const types: Function[] = [String, Boolean, Number, Array, Object];
return !types.includes(metatype);
}
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