UNPKG

2.51 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const constants_1 = require("@nestjs/common/constants");
4const random_string_generator_util_1 = require("@nestjs/common/utils/random-string-generator.util");
5const fast_safe_stringify_1 = require("fast-safe-stringify");
6const hash = require("object-hash");
7class ModuleTokenFactory {
8 constructor() {
9 this.moduleIdsCache = new WeakMap();
10 }
11 create(metatype, scope, dynamicModuleMetadata) {
12 const moduleId = this.getModuleId(metatype);
13 const moduleScope = this.reflectScope(metatype);
14 const isSingleScoped = moduleScope === true;
15 const opaqueToken = {
16 id: moduleId,
17 module: this.getModuleName(metatype),
18 dynamic: this.getDynamicMetadataToken(dynamicModuleMetadata),
19 scope: isSingleScoped ? this.getScopeStack(scope) : moduleScope,
20 };
21 return hash(opaqueToken, { ignoreUnknown: true });
22 }
23 getDynamicMetadataToken(dynamicModuleMetadata) {
24 // Uses safeStringify instead of JSON.stringify to support circular dynamic modules
25 // The replacer function is also required in order to obtain real class names
26 // instead of the unified "Function" key
27 return dynamicModuleMetadata
28 ? fast_safe_stringify_1.default(dynamicModuleMetadata, this.replacer)
29 : '';
30 }
31 getScopeStack(scope) {
32 const reversedScope = scope.reverse();
33 const firstGlobalIndex = reversedScope.findIndex(s => this.reflectScope(s) === 'global');
34 scope.reverse();
35 const stack = firstGlobalIndex >= 0
36 ? scope.slice(scope.length - firstGlobalIndex - 1)
37 : scope;
38 return stack.map(module => module.name);
39 }
40 getModuleId(metatype) {
41 let moduleId = this.moduleIdsCache.get(metatype);
42 if (moduleId) {
43 return moduleId;
44 }
45 moduleId = random_string_generator_util_1.randomStringGenerator();
46 this.moduleIdsCache.set(metatype, moduleId);
47 return moduleId;
48 }
49 getModuleName(metatype) {
50 return metatype.name;
51 }
52 reflectScope(metatype) {
53 const scope = Reflect.getMetadata(constants_1.SHARED_MODULE_METADATA, metatype);
54 return scope ? scope : 'global';
55 }
56 replacer(key, value) {
57 if (typeof value === 'function') {
58 return value.name;
59 }
60 return value;
61 }
62}
63exports.ModuleTokenFactory = ModuleTokenFactory;