|
1 | 1 | import { Type } from '@nestjs/common'; |
| 2 | +import { isObject } from '@nestjs/common/utils/shared.utils'; |
2 | 3 |
|
3 | 4 | /** |
4 | 5 | * Helper class providing Nest reflection capabilities. |
@@ -32,12 +33,55 @@ export class Reflector { |
32 | 33 | * @param targets context (decorated objects) to retrieve metadata from |
33 | 34 | * |
34 | 35 | */ |
35 | | - public getAll<TResult extends any[] = any, TKey = any>( |
| 36 | + public getAll<TResult extends any[] = any[], TKey = any>( |
36 | 37 | metadataKey: TKey, |
37 | 38 | targets: (Type<any> | Function)[], |
38 | 39 | ): TResult { |
39 | 40 | return (targets || []).map(target => |
40 | 41 | Reflect.getMetadata(metadataKey, target), |
41 | 42 | ) as TResult; |
42 | 43 | } |
| 44 | + |
| 45 | + /** |
| 46 | + * Retrieve metadata for a specified key for a specified set of targets and concat results. |
| 47 | + * |
| 48 | + * @param metadataKey lookup key for metadata to retrieve |
| 49 | + * @param targets context (decorated objects) to retrieve metadata from |
| 50 | + * |
| 51 | + */ |
| 52 | + public getAllAndConcat<TResult extends any[] = any[], TKey = any>( |
| 53 | + metadataKey: TKey, |
| 54 | + targets: (Type<any> | Function)[], |
| 55 | + ): TResult { |
| 56 | + const metadataCollection = this.getAll(metadataKey, targets); |
| 57 | + return metadataCollection.reduce((a, b) => { |
| 58 | + if (Array.isArray(a)) { |
| 59 | + return a.concat(b); |
| 60 | + } |
| 61 | + if (isObject(a) && isObject(b)) { |
| 62 | + return { |
| 63 | + ...a, |
| 64 | + ...b, |
| 65 | + }; |
| 66 | + } |
| 67 | + return b; |
| 68 | + }); |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Retrieve metadata for a specified key for a specified set of targets and return a first not undefined value. |
| 73 | + * |
| 74 | + * @param metadataKey lookup key for metadata to retrieve |
| 75 | + * @param targets context (decorated objects) to retrieve metadata from |
| 76 | + * |
| 77 | + */ |
| 78 | + public getAllAndOverride<TResult = any, TKey = any>( |
| 79 | + metadataKey: TKey, |
| 80 | + targets: (Type<any> | Function)[], |
| 81 | + ): TResult { |
| 82 | + const metadataCollection = this.getAll(metadataKey, targets).filter( |
| 83 | + item => item !== undefined, |
| 84 | + ); |
| 85 | + return metadataCollection[0]; |
| 86 | + } |
43 | 87 | } |
0 commit comments