UNPKG

2.06 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 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, dynamicModuleMetadata) {
12 const moduleId = this.getModuleId(metatype);
13 const opaqueToken = {
14 id: moduleId,
15 module: this.getModuleName(metatype),
16 dynamic: this.getDynamicMetadataToken(dynamicModuleMetadata),
17 };
18 return hash(opaqueToken, { ignoreUnknown: true });
19 }
20 getDynamicMetadataToken(dynamicModuleMetadata) {
21 // Uses safeStringify instead of JSON.stringify to support circular dynamic modules
22 // The replacer function is also required in order to obtain real class names
23 // instead of the unified "Function" key
24 return dynamicModuleMetadata
25 ? fast_safe_stringify_1.default(dynamicModuleMetadata, this.replacer)
26 : '';
27 }
28 getModuleId(metatype) {
29 let moduleId = this.moduleIdsCache.get(metatype);
30 if (moduleId) {
31 return moduleId;
32 }
33 moduleId = random_string_generator_util_1.randomStringGenerator();
34 this.moduleIdsCache.set(metatype, moduleId);
35 return moduleId;
36 }
37 getModuleName(metatype) {
38 return metatype.name;
39 }
40 replacer(key, value) {
41 if (typeof value === 'function') {
42 const funcAsString = value.toString();
43 const isClass = /^class\s/.test(funcAsString);
44 if (isClass) {
45 return value.name;
46 }
47 return hash(funcAsString, { ignoreUnknown: true });
48 }
49 if (typeof value === 'symbol') {
50 return value.toString();
51 }
52 return value;
53 }
54}
55exports.ModuleTokenFactory = ModuleTokenFactory;