Skip to content

Commit

Permalink
fix: handle empty body validation
Browse files Browse the repository at this point in the history
  • Loading branch information
ggurkal committed Jun 16, 2022
1 parent 8c3a820 commit a0b85d7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/internals/validateObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { loadPackage } from './loadPackage';

export async function validateObject(
cls: ClassConstructor<any>,
value: Record<string, string>,
value: string | Record<string, any>,
validatorOptions?: ValidationPipeOptions
): Promise<any> {
const classValidator = loadPackage('class-validator');
Expand All @@ -19,6 +19,10 @@ export async function validateObject(
return value;
}

if (value == null || (typeof value === 'string' && !value.trim().length)) {
value = {};
}

const bodyValue = classTransformer.plainToClass(cls, value, {
enableImplicitConversion: true,
...validatorOptions?.transformOptions
Expand Down
28 changes: 28 additions & 0 deletions lib/pipes/validators/validation.pipe.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { IsEmail, IsNotEmpty } from 'class-validator';
import { BadRequestException } from '../../exceptions';
import * as lp from '../../internals/loadPackage';
import { ValidationPipe } from './validation.pipe';

Expand Down Expand Up @@ -37,4 +39,30 @@ describe('ValidationPipe', () => {
firstName: 'Uncle',
lastName: 'Bob'
}));

it('Should throw for an "undefined" body.', () => {
class DTO {
@IsNotEmpty()
@IsEmail()
public email!: string;

@IsNotEmpty()
public name!: string;
}

expect(ValidationPipe()(undefined, { metaType: DTO })).rejects.toThrowError(BadRequestException);
});

it('Should throw for an empty string body.', () => {
class DTO {
@IsNotEmpty()
@IsEmail()
public email!: string;

@IsNotEmpty()
public name!: string;
}

expect(ValidationPipe()('', { metaType: DTO })).rejects.toThrowError(BadRequestException);
});
});

0 comments on commit a0b85d7

Please sign in to comment.