mirror of
https://github.com/nestjs/nest.git
synced 2026-02-21 23:11:44 +00:00
feat(@nestjs/common) improve the ValidationPipe
This commit is contained in:
1124
package-lock.json
generated
1124
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -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",
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user