UNPKG

2.36 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, options = {}) {
13 const instanceLinksForGivenToken = this.instanceLinks.get(token);
14 if (!instanceLinksForGivenToken) {
15 throw new unknown_element_exception_1.UnknownElementException(this.getInstanceNameByToken(token));
16 }
17 if (options.each) {
18 return instanceLinksForGivenToken;
19 }
20 const instanceLink = options.moduleId
21 ? instanceLinksForGivenToken.find(item => item.moduleId === options.moduleId)
22 : instanceLinksForGivenToken[instanceLinksForGivenToken.length - 1];
23 if (!instanceLink) {
24 throw new unknown_element_exception_1.UnknownElementException(this.getInstanceNameByToken(token));
25 }
26 return instanceLink;
27 }
28 initialize() {
29 const modules = this.container.getModules();
30 modules.forEach(moduleRef => {
31 const { providers, injectables, controllers } = moduleRef;
32 providers.forEach((wrapper, token) => this.addLink(wrapper, token, moduleRef, 'providers'));
33 injectables.forEach((wrapper, token) => this.addLink(wrapper, token, moduleRef, 'injectables'));
34 controllers.forEach((wrapper, token) => this.addLink(wrapper, token, moduleRef, 'controllers'));
35 });
36 }
37 addLink(wrapper, token, moduleRef, collectionName) {
38 const instanceLink = {
39 moduleId: moduleRef.id,
40 wrapperRef: wrapper,
41 collection: moduleRef[collectionName],
42 token,
43 };
44 const existingLinks = this.instanceLinks.get(token);
45 if (!existingLinks) {
46 this.instanceLinks.set(token, [instanceLink]);
47 }
48 else {
49 existingLinks.push(instanceLink);
50 }
51 }
52 getInstanceNameByToken(token) {
53 return (0, shared_utils_1.isFunction)(token) ? token?.name : token;
54 }
55}
56exports.InstanceLinksHost = InstanceLinksHost;