feature(@nestjs/common) validation pipe

This commit is contained in:
Kamil Myśliwiec
2017-11-21 13:53:01 +01:00
6 changed files with 83 additions and 0 deletions

View File

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

View File

@@ -29,4 +29,5 @@ export {
WsExceptionFilter,
NestInterceptor,
} from './interfaces';
export * from './pipes';
export * from './services/logger.service';

View File

@@ -0,0 +1 @@
export * from './validation.pipe';

View File

@@ -0,0 +1,30 @@
import { HttpException } from '@nestjs/core';
import {
PipeTransform,
Pipe,
ArgumentMetadata,
HttpStatus,
} from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
@Pipe()
export class ValidationPipe implements PipeTransform<any> {
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);
if (errors.length > 0) {
throw new HttpException('Validation failed', HttpStatus.BAD_REQUEST);
}
return entity;
}
private toValidate(metatype): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find(type => metatype === type);
}
}

View File

@@ -0,0 +1,48 @@
import * as sinon from 'sinon';
import { expect } from 'chai';
import { ArgumentMetadata } from './../../interfaces';
import { IsString } from 'class-validator';
import { ValidationPipe } from './../../pipes/validation.pipe';
class TestModel {
constructor() {}
@IsString() public prop1: string;
@IsString() public prop2: string;
}
describe('ValidationPipe', () => {
let target: ValidationPipe;
const metadata: ArgumentMetadata = {
type: 'body',
metatype: TestModel,
data: '',
};
beforeEach(() => {
target = new ValidationPipe();
});
describe('transform', () => {
describe('when metadata is empty or undefined', () => {
it('should return the value unchanged', async () => {
const testObj = { prop1: 'value1', prop2: 'value2' };
expect(await target.transform(testObj, {} as any)).to.equal(testObj);
expect(await target.transform(testObj, {} as any)).to.not.be.instanceOf(
TestModel,
);
});
});
describe('when metadata contains a class', () => {
it('should return an instance of the class', async () => {
const testObj = { prop1: 'value1', prop2: 'value2' };
const result = await target.transform(testObj, metadata);
expect(result).to.be.instanceOf(TestModel);
});
});
describe('when validation vails', () => {
it('should throw an error', async () => {
const testObj = { prop1: 'value1' };
return expect(target.transform(testObj, metadata)).to.be.rejected;
});
});
});
});

View File

@@ -12,6 +12,7 @@
true,
"single"
],
"indent": false,
"ordered-imports": [
false
],