forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse-enum.pipe.ts
64 lines (58 loc) 路 1.79 KB
/
parse-enum.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
62
63
64
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 ParseEnumPipeOptions {
errorHttpStatusCode?: ErrorHttpStatusCode;
exceptionFactory?: (error: string) => any;
}
/**
* Defines the built-in ParseEnum Pipe
*
* @see [Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes)
*
* @publicApi
*/
@Injectable()
export class ParseEnumPipe<T = any> implements PipeTransform<T> {
protected exceptionFactory: (error: string) => any;
constructor(
protected readonly enumType: T,
@Optional() options?: ParseEnumPipeOptions,
) {
if (!enumType) {
throw new Error(
`"ParseEnumPipe" requires "enumType" argument specified (to validate input values).`,
);
}
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: T, metadata: ArgumentMetadata): Promise<T> {
if (!this.isEnum(value)) {
throw this.exceptionFactory(
'Validation failed (enum string is expected)',
);
}
return value;
}
protected isEnum(value: T): boolean {
const enumValues = Object.keys(this.enumType).map(
item => this.enumType[item],
);
return enumValues.includes(value);
}
}