forked from nest-cloud/nestcloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadbalance.explorer.ts
59 lines (54 loc) · 2.12 KB
/
loadbalance.explorer.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
import { Injectable, OnModuleInit } from '@nestjs/common';
import { DiscoveryService } from '@nestjs/core';
import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper';
import { LoadbalanceMetadataAccessor } from './loadbalance-metadata.accessor';
import { LoadbalanceOrchestrator } from './loadbalance.orchestrator';
import { Rule } from './interfaces/rule.interface';
import { Scanner } from '@nestcloud/common';
import { LoadbalanceRuleRegistry } from './loadbalance-rule.registry';
@Injectable()
export class LoadbalanceExplorer implements OnModuleInit {
constructor(
private readonly discoveryService: DiscoveryService,
private readonly metadataAccessor: LoadbalanceMetadataAccessor,
private readonly loadbalanceOrchestrator: LoadbalanceOrchestrator,
private readonly loadbalanceRuleRegistry: LoadbalanceRuleRegistry,
private readonly scanner: Scanner,
) {
}
async onModuleInit() {
this.explore();
await this.loadbalanceOrchestrator.mountChooses();
}
explore() {
const providers: InstanceWrapper[] = [
...this.discoveryService.getProviders(),
...this.discoveryService.getControllers(),
];
providers.forEach((wrapper: InstanceWrapper) => {
const { instance } = wrapper;
if (!instance || typeof instance === 'string') {
return;
}
this.lookupKeyValues(instance);
this.lookupRules(instance);
});
}
lookupRules(instance: Function) {
const Rules = this.metadataAccessor.getRules(instance.constructor);
if (Rules) {
Rules.forEach(ref => {
const rule = this.scanner.findInjectable<Rule>(ref as Function);
if (rule) {
this.loadbalanceRuleRegistry.addRule((ref as Function).name, rule);
}
});
}
}
lookupKeyValues(instance: Function) {
const chooses = this.metadataAccessor.getChooses(instance);
if (chooses) {
this.loadbalanceOrchestrator.addChooses(instance, chooses);
}
}
}