Skip to content

Commit 1279602

Browse files
Merge branch 'oschweitzer-parseInt-pipe-improvement'
2 parents 2296d30 + ec6b891 commit 1279602

2 files changed

Lines changed: 11 additions & 8 deletions

File tree

src/common/pipes/parse-int.pipe.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
import { BadRequestException } from '../exceptions/bad-request.exception';
22
import { PipeTransform } from '../interfaces/pipe-transform.interface';
3-
import { Pipe, ArgumentMetadata } from '../index';
3+
import { ArgumentMetadata, Pipe } from '../index';
44

55
@Pipe()
66
export class ParseIntPipe implements PipeTransform<string> {
7-
public async transform(value: string, metadata: ArgumentMetadata) {
8-
const val = parseInt(value, 10);
9-
if (isNaN(val)) {
10-
throw new BadRequestException('Validation failed');
7+
async transform(value: string, metadata: ArgumentMetadata): Promise<number> {
8+
const isNumeric =
9+
'string' === typeof value &&
10+
!isNaN(parseFloat(value)) &&
11+
isFinite(value as any);
12+
if (!isNumeric) {
13+
throw new BadRequestException('Numeric string is expected');
1114
}
12-
return val;
15+
return parseInt(value, 10);
1316
}
1417
}

src/common/test/pipes/parse-int.pipe.spec.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ describe('ParseIntPipe', () => {
1717
);
1818
});
1919
});
20-
describe('when validation vails', () => {
20+
describe('when validation fails', () => {
2121
it('should throw an error', async () => {
22-
return expect(target.transform('notanumber!', {} as any)).to.be
22+
return expect(target.transform('123abc', {} as any)).to.be
2323
.rejected;
2424
});
2525
});

0 commit comments

Comments
 (0)