UNPKG

2.95 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.GuardsContextCreator = void 0;
4const constants_1 = require("@nestjs/common/constants");
5const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
6const iterare_1 = require("iterare");
7const context_creator_1 = require("../helpers/context-creator");
8const constants_2 = require("../injector/constants");
9class GuardsContextCreator extends context_creator_1.ContextCreator {
10 constructor(container, config) {
11 super();
12 this.container = container;
13 this.config = config;
14 }
15 create(instance, callback, module, contextId = constants_2.STATIC_CONTEXT, inquirerId) {
16 this.moduleContext = module;
17 return this.createContext(instance, callback, constants_1.GUARDS_METADATA, contextId, inquirerId);
18 }
19 createConcreteContext(metadata, contextId = constants_2.STATIC_CONTEXT, inquirerId) {
20 if ((0, shared_utils_1.isEmpty)(metadata)) {
21 return [];
22 }
23 return (0, iterare_1.iterate)(metadata)
24 .filter((guard) => guard && (guard.name || guard.canActivate))
25 .map(guard => this.getGuardInstance(guard, contextId, inquirerId))
26 .filter((guard) => guard && (0, shared_utils_1.isFunction)(guard.canActivate))
27 .toArray();
28 }
29 getGuardInstance(metatype, contextId = constants_2.STATIC_CONTEXT, inquirerId) {
30 const isObject = metatype.canActivate;
31 if (isObject) {
32 return metatype;
33 }
34 const instanceWrapper = this.getInstanceByMetatype(metatype);
35 if (!instanceWrapper) {
36 return null;
37 }
38 const instanceHost = instanceWrapper.getInstanceByContextId(contextId, inquirerId);
39 return instanceHost && instanceHost.instance;
40 }
41 getInstanceByMetatype(metatype) {
42 if (!this.moduleContext) {
43 return;
44 }
45 const collection = this.container.getModules();
46 const moduleRef = collection.get(this.moduleContext);
47 if (!moduleRef) {
48 return;
49 }
50 const injectables = moduleRef.injectables;
51 return injectables.get(metatype);
52 }
53 getGlobalMetadata(contextId = constants_2.STATIC_CONTEXT, inquirerId) {
54 if (!this.config) {
55 return [];
56 }
57 const globalGuards = this.config.getGlobalGuards();
58 if (contextId === constants_2.STATIC_CONTEXT && !inquirerId) {
59 return globalGuards;
60 }
61 const scopedGuardWrappers = this.config.getGlobalRequestGuards();
62 const scopedGuards = (0, iterare_1.iterate)(scopedGuardWrappers)
63 .map(wrapper => wrapper.getInstanceByContextId(contextId, inquirerId))
64 .filter(host => !!host)
65 .map(host => host.instance)
66 .toArray();
67 return globalGuards.concat(scopedGuards);
68 }
69}
70exports.GuardsContextCreator = GuardsContextCreator;