feat(@nestjs/common) improve the ValidationPipe

This commit is contained in:
Frédéric Woelffel
2018-01-29 14:30:04 +01:00
parent 18125677b2
commit dc24a2072e
3 changed files with 1119 additions and 28 deletions

1124
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -24,7 +24,7 @@
"@nestjs/testing": "^4.0.0",
"@nestjs/websockets": "^4.0.0",
"class-transformer": "^0.1.8",
"class-validator": "^0.7.3",
"class-validator": "^0.8.1",
"cli-color": "^1.1.0",
"engine.io-client": "^3.1.1",
"express": "^4.16.2",

View File

@@ -5,19 +5,36 @@ import { ArgumentMetadata, BadRequestException } from '../index';
import { isNil } from '../utils/shared.utils';
import { Pipe } from './../decorators/core/component.decorator';
export interface ValidationPipeOptions {
transform?: boolean;
strip?: boolean;
reject?: boolean;
}
@Pipe()
export class ValidationPipe implements PipeTransform<any> {
private shouldTransform: boolean;
private shouldStrip: boolean;
private shouldReject: boolean;
constructor(options?: ValidationPipeOptions) {
this.shouldTransform = options && (options.transform || options.strip || options.reject);
this.shouldStrip = options && (options.strip || options.reject);
this.shouldReject = options && options.reject;
}
public async transform(value, metadata: ArgumentMetadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const entity = plainToClass(metatype, value);
const errors = await validate(entity);
const errors = await validate(entity, { whitelist: this.shouldStrip, forbidNonWhitelisted: this.shouldReject });
if (errors.length > 0) {
throw new BadRequestException(errors);
}
return value;
return this.shouldTransform ? entity : value;
}
private toValidate(metatype): boolean {