forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse-float.pipe.ts
61 lines (55 loc) · 1.75 KB
/
parse-float.pipe.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { ArgumentMetadata, HttpStatus, Injectable, Optional } from '../index';
import { PipeTransform } from '../interfaces/features/pipe-transform.interface';
import {
ErrorHttpStatusCode,
HttpErrorByCode,
} from '../utils/http-error-by-code.util';
export interface ParseFloatPipeOptions {
errorHttpStatusCode?: ErrorHttpStatusCode;
exceptionFactory?: (error: string) => any;
}
/**
* Defines the built-in ParseFloat Pipe
*
* @see [Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes)
*
* @publicApi
*/
@Injectable()
export class ParseFloatPipe implements PipeTransform<string> {
protected exceptionFactory: (error: string) => any;
constructor(@Optional() options?: ParseFloatPipeOptions) {
options = options || {};
const { exceptionFactory, errorHttpStatusCode = HttpStatus.BAD_REQUEST } =
options;
this.exceptionFactory =
exceptionFactory ||
(error => new HttpErrorByCode[errorHttpStatusCode](error));
}
/**
* Method that accesses and performs optional transformation on argument for
* in-flight requests.
*
* @param value currently processed route argument
* @param metadata contains metadata about the currently processed route argument
*/
async transform(value: string, metadata: ArgumentMetadata): Promise<number> {
if (!this.isNumeric(value)) {
throw this.exceptionFactory(
'Validation failed (numeric string is expected)',
);
}
return parseFloat(value);
}
/**
* @param value currently processed route argument
* @returns `true` if `value` is a valid float number
*/
protected isNumeric(value: string): boolean {
return (
['string', 'number'].includes(typeof value) &&
!isNaN(parseFloat(value)) &&
isFinite(value as any)
);
}
}