Skip to content

Commit 24e41e3

Browse files
committed
chore(pipes): extract nullable check to a function
1 parent 918e1c4 commit 24e41e3

File tree

3 files changed

+15
-8
lines changed

3 files changed

+15
-8
lines changed

lib/pipes/parseBoolean.pipe.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
import { BadRequestException } from '../exceptions';
22
import type { ParameterPipe, PipeOptions } from './ParameterPipe';
3+
import { validatePipeOptions } from './validatePipeOptions';
34

45
export function ParseBooleanPipe(options?: PipeOptions): ParameterPipe<boolean> {
56
return (value: any, name?: string) => {
6-
if (!options?.nullable && value == null) {
7-
throw new BadRequestException(name ? `${name} is a required parameter.` : 'Missing a required parameter.');
8-
}
7+
validatePipeOptions(value, name, options);
98

109
if (value === true || value === 'true') {
1110
return true;
@@ -15,6 +14,6 @@ export function ParseBooleanPipe(options?: PipeOptions): ParameterPipe<boolean>
1514
return false;
1615
}
1716

18-
throw new BadRequestException('Validation failed (boolean string is expected)');
17+
throw new BadRequestException(`Validation failed${name ? ` for ${name}` : ''} (boolean string is expected)`);
1918
};
2019
}

lib/pipes/parseNumber.pipe.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
import { BadRequestException } from '../exceptions';
22
import type { ParameterPipe, PipeOptions } from './ParameterPipe';
3+
import { validatePipeOptions } from './validatePipeOptions';
34

45
export function ParseNumberPipe(options?: PipeOptions): ParameterPipe<number> {
56
return (value: any, name?: string) => {
6-
if (!options?.nullable && value == null) {
7-
throw new BadRequestException(name ? `${name} is a required parameter.` : 'Missing a required parameter');
8-
}
7+
validatePipeOptions(value, name, options);
98

109
const isNumeric = ['string', 'number'].includes(typeof value) && !isNaN(parseFloat(value)) && isFinite(value);
1110
if (!isNumeric) {
12-
throw new BadRequestException('Validation failed (numeric string is expected)');
11+
throw new BadRequestException(`Validation failed${name ? ` for ${name}` : ''} (numeric string is expected)`);
1312
}
13+
1414
return parseFloat(value);
1515
};
1616
}

lib/pipes/validatePipeOptions.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { BadRequestException } from '../exceptions';
2+
import type { PipeOptions } from './ParameterPipe';
3+
4+
export function validatePipeOptions(value: any, name?: string, options?: PipeOptions) {
5+
if (!options?.nullable && (value == null || value.toString().trim().length === 0)) {
6+
throw new BadRequestException(name ? `${name} is a required parameter.` : 'Missing a required parameter.');
7+
}
8+
}

0 commit comments

Comments
 (0)