-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
module-token-factory.ts
63 lines (57 loc) 路 1.99 KB
/
module-token-factory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { DynamicModule } from '@nestjs/common';
import { Type } from '@nestjs/common/interfaces/type.interface';
import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util';
import { isFunction, isSymbol } from '@nestjs/common/utils/shared.utils';
import stringify from 'fast-safe-stringify';
import * as hash from 'object-hash';
export class ModuleTokenFactory {
private readonly moduleIdsCache = new WeakMap<Type<unknown>, string>();
public create(
metatype: Type<unknown>,
dynamicModuleMetadata?: Partial<DynamicModule> | undefined,
): string {
const moduleId = this.getModuleId(metatype);
const opaqueToken = {
id: moduleId,
module: this.getModuleName(metatype),
dynamic: this.getDynamicMetadataToken(dynamicModuleMetadata),
};
return hash(opaqueToken, { ignoreUnknown: true });
}
public getDynamicMetadataToken(
dynamicModuleMetadata: Partial<DynamicModule> | undefined,
): string {
// Uses safeStringify instead of JSON.stringify to support circular dynamic modules
// The replacer function is also required in order to obtain real class names
// instead of the unified "Function" key
return dynamicModuleMetadata
? stringify(dynamicModuleMetadata, this.replacer)
: '';
}
public getModuleId(metatype: Type<unknown>): string {
let moduleId = this.moduleIdsCache.get(metatype);
if (moduleId) {
return moduleId;
}
moduleId = randomStringGenerator();
this.moduleIdsCache.set(metatype, moduleId);
return moduleId;
}
public getModuleName(metatype: Type<any>): string {
return metatype.name;
}
private replacer(key: string, value: any) {
if (isFunction(value)) {
const funcAsString = value.toString();
const isClass = /^class\s/.test(funcAsString);
if (isClass) {
return value.name;
}
return hash(funcAsString, { ignoreUnknown: true });
}
if (isSymbol(value)) {
return value.toString();
}
return value;
}
}