UNPKG

2.22 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.InstanceLinksHost = void 0;
4const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
5const unknown_element_exception_1 = require("../errors/exceptions/unknown-element.exception");
6class InstanceLinksHost {
7 constructor(container) {
8 this.container = container;
9 this.instanceLinks = new Map();
10 this.initialize();
11 }
12 get(token, moduleId) {
13 const modulesMap = this.instanceLinks.get(token);
14 if (!modulesMap) {
15 throw new unknown_element_exception_1.UnknownElementException(this.getInstanceNameByToken(token));
16 }
17 const instanceLink = moduleId
18 ? modulesMap.find(item => item.moduleId === moduleId)
19 : modulesMap[modulesMap.length - 1];
20 if (!instanceLink) {
21 throw new unknown_element_exception_1.UnknownElementException(this.getInstanceNameByToken(token));
22 }
23 return instanceLink;
24 }
25 initialize() {
26 const modules = this.container.getModules();
27 modules.forEach(moduleRef => {
28 const { providers, injectables, controllers } = moduleRef;
29 providers.forEach((wrapper, token) => this.addLink(wrapper, token, moduleRef, 'providers'));
30 injectables.forEach((wrapper, token) => this.addLink(wrapper, token, moduleRef, 'injectables'));
31 controllers.forEach((wrapper, token) => this.addLink(wrapper, token, moduleRef, 'controllers'));
32 });
33 }
34 addLink(wrapper, token, moduleRef, collectionName) {
35 const instanceLink = {
36 moduleId: moduleRef.id,
37 wrapperRef: wrapper,
38 collection: moduleRef[collectionName],
39 token,
40 };
41 const existingLinks = this.instanceLinks.get(token);
42 if (!existingLinks) {
43 this.instanceLinks.set(token, [instanceLink]);
44 }
45 else {
46 existingLinks.push(instanceLink);
47 }
48 }
49 getInstanceNameByToken(token) {
50 return (0, shared_utils_1.isFunction)(token) ? token === null || token === void 0 ? void 0 : token.name : token;
51 }
52}
53exports.InstanceLinksHost = InstanceLinksHost;