-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
reflector.service.ts
97 lines (92 loc) 路 2.66 KB
/
reflector.service.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { Type } from '@nestjs/common';
import { isEmpty, isObject } from '@nestjs/common/utils/shared.utils';
/**
* Helper class providing Nest reflection capabilities.
*
* @see [Reflection](https://docs.nestjs.com/guards#putting-it-all-together)
*
* @publicApi
*/
export class Reflector {
/**
* Retrieve metadata for a specified key for a specified target.
*
* @example
* `const roles = this.reflector.get<string[]>('roles', context.getHandler());`
*
* @param metadataKey lookup key for metadata to retrieve
* @param target context (decorated object) to retrieve metadata from
*
*/
public get<TResult = any, TKey = any>(
metadataKey: TKey,
target: Type<any> | Function,
): TResult {
return Reflect.getMetadata(metadataKey, target);
}
/**
* Retrieve metadata for a specified key for a specified set of targets.
*
* @param metadataKey lookup key for metadata to retrieve
* @param targets context (decorated objects) to retrieve metadata from
*
*/
public getAll<TResult extends any[] = any[], TKey = any>(
metadataKey: TKey,
targets: (Type<any> | Function)[],
): TResult {
return (targets || []).map(target =>
this.get(metadataKey, target),
) as TResult;
}
/**
* Retrieve metadata for a specified key for a specified set of targets and merge results.
*
* @param metadataKey lookup key for metadata to retrieve
* @param targets context (decorated objects) to retrieve metadata from
*
*/
public getAllAndMerge<TResult extends any[] = any[], TKey = any>(
metadataKey: TKey,
targets: (Type<any> | Function)[],
): TResult {
const metadataCollection = this.getAll<TResult, TKey>(
metadataKey,
targets,
).filter(item => item !== undefined);
if (isEmpty(metadataCollection)) {
return metadataCollection as TResult;
}
return metadataCollection.reduce((a, b) => {
if (Array.isArray(a)) {
return a.concat(b);
}
if (isObject(a) && isObject(b)) {
return {
...a,
...b,
};
}
return [a, b];
});
}
/**
* Retrieve metadata for a specified key for a specified set of targets and return a first not undefined value.
*
* @param metadataKey lookup key for metadata to retrieve
* @param targets context (decorated objects) to retrieve metadata from
*
*/
public getAllAndOverride<TResult = any, TKey = any>(
metadataKey: TKey,
targets: (Type<any> | Function)[],
): TResult {
for (const target of targets) {
const result = this.get(metadataKey, target);
if (result !== undefined) {
return result;
}
}
return undefined;
}
}