UNPKG

2.54 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.Reflector = void 0;
4const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
5/**
6 * Helper class providing Nest reflection capabilities.
7 *
8 * @see [Reflection](https://docs.nestjs.com/guards#putting-it-all-together)
9 *
10 * @publicApi
11 */
12class Reflector {
13 /**
14 * Retrieve metadata for a specified key for a specified target.
15 *
16 * @example
17 * `const roles = this.reflector.get<string[]>('roles', context.getHandler());`
18 *
19 * @param metadataKey lookup key for metadata to retrieve
20 * @param target context (decorated object) to retrieve metadata from
21 *
22 */
23 get(metadataKey, target) {
24 return Reflect.getMetadata(metadataKey, target);
25 }
26 /**
27 * Retrieve metadata for a specified key for a specified set of targets.
28 *
29 * @param metadataKey lookup key for metadata to retrieve
30 * @param targets context (decorated objects) to retrieve metadata from
31 *
32 */
33 getAll(metadataKey, targets) {
34 return (targets || []).map(target => Reflect.getMetadata(metadataKey, target));
35 }
36 /**
37 * Retrieve metadata for a specified key for a specified set of targets and merge results.
38 *
39 * @param metadataKey lookup key for metadata to retrieve
40 * @param targets context (decorated objects) to retrieve metadata from
41 *
42 */
43 getAllAndMerge(metadataKey, targets) {
44 const metadataCollection = this.getAll(metadataKey, targets).filter(item => item !== undefined);
45 if ((0, shared_utils_1.isEmpty)(metadataCollection)) {
46 return metadataCollection;
47 }
48 return metadataCollection.reduce((a, b) => {
49 if (Array.isArray(a)) {
50 return a.concat(b);
51 }
52 if ((0, shared_utils_1.isObject)(a) && (0, shared_utils_1.isObject)(b)) {
53 return Object.assign(Object.assign({}, a), b);
54 }
55 return [a, b];
56 });
57 }
58 /**
59 * Retrieve metadata for a specified key for a specified set of targets and return a first not undefined value.
60 *
61 * @param metadataKey lookup key for metadata to retrieve
62 * @param targets context (decorated objects) to retrieve metadata from
63 *
64 */
65 getAllAndOverride(metadataKey, targets) {
66 const metadataCollection = this.getAll(metadataKey, targets).filter(item => item !== undefined);
67 return metadataCollection[0];
68 }
69}
70exports.Reflector = Reflector;