UNPKG

2.16 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.ModuleTokenFactory = void 0;
4const random_string_generator_util_1 = require("@nestjs/common/utils/random-string-generator.util");
5const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
6const fast_safe_stringify_1 = require("fast-safe-stringify");
7const hash = require("object-hash");
8class ModuleTokenFactory {
9 constructor() {
10 this.moduleIdsCache = new WeakMap();
11 }
12 create(metatype, dynamicModuleMetadata) {
13 const moduleId = this.getModuleId(metatype);
14 const opaqueToken = {
15 id: moduleId,
16 module: this.getModuleName(metatype),
17 dynamic: this.getDynamicMetadataToken(dynamicModuleMetadata),
18 };
19 return hash(opaqueToken, { ignoreUnknown: true });
20 }
21 getDynamicMetadataToken(dynamicModuleMetadata) {
22 // Uses safeStringify instead of JSON.stringify to support circular dynamic modules
23 // The replacer function is also required in order to obtain real class names
24 // instead of the unified "Function" key
25 return dynamicModuleMetadata
26 ? (0, fast_safe_stringify_1.default)(dynamicModuleMetadata, this.replacer)
27 : '';
28 }
29 getModuleId(metatype) {
30 let moduleId = this.moduleIdsCache.get(metatype);
31 if (moduleId) {
32 return moduleId;
33 }
34 moduleId = (0, random_string_generator_util_1.randomStringGenerator)();
35 this.moduleIdsCache.set(metatype, moduleId);
36 return moduleId;
37 }
38 getModuleName(metatype) {
39 return metatype.name;
40 }
41 replacer(key, value) {
42 if ((0, shared_utils_1.isFunction)(value)) {
43 const funcAsString = value.toString();
44 const isClass = /^class\s/.test(funcAsString);
45 if (isClass) {
46 return value.name;
47 }
48 return hash(funcAsString, { ignoreUnknown: true });
49 }
50 if ((0, shared_utils_1.isSymbol)(value)) {
51 return value.toString();
52 }
53 return value;
54 }
55}
56exports.ModuleTokenFactory = ModuleTokenFactory;