Skip to content

Commit

Permalink
Merge branch 'oschweitzer-parseInt-pipe-improvement'
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Feb 5, 2018
2 parents 2296d30 + ec6b891 commit 1279602
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
15 changes: 9 additions & 6 deletions src/common/pipes/parse-int.pipe.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { BadRequestException } from '../exceptions/bad-request.exception';
import { PipeTransform } from '../interfaces/pipe-transform.interface';
import { Pipe, ArgumentMetadata } from '../index';
import { ArgumentMetadata, Pipe } from '../index';

@Pipe()
export class ParseIntPipe implements PipeTransform<string> {
public async transform(value: string, metadata: ArgumentMetadata) {
const val = parseInt(value, 10);
if (isNaN(val)) {
throw new BadRequestException('Validation failed');
async transform(value: string, metadata: ArgumentMetadata): Promise<number> {
const isNumeric =
'string' === typeof value &&
!isNaN(parseFloat(value)) &&
isFinite(value as any);
if (!isNumeric) {
throw new BadRequestException('Numeric string is expected');
}
return val;
return parseInt(value, 10);
}
}
4 changes: 2 additions & 2 deletions src/common/test/pipes/parse-int.pipe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ describe('ParseIntPipe', () => {
);
});
});
describe('when validation vails', () => {
describe('when validation fails', () => {
it('should throw an error', async () => {
return expect(target.transform('notanumber!', {} as any)).to.be
return expect(target.transform('123abc', {} as any)).to.be
.rejected;
});
});
Expand Down

0 comments on commit 1279602

Please sign in to comment.