forked from nest-cloud/nestcloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadbalance.orchestrator.ts
43 lines (37 loc) · 1.29 KB
/
loadbalance.orchestrator.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
import { Injectable } from '@nestjs/common';
import { Scanner, ILoadbalance, IServer } from '@nestcloud/common';
import { ChooseMetadata } from './interfaces/choose-metadata.interface';
import { InjectLoadbalance } from './decorators/inject-loadbalance.decorator';
interface Choose {
service: string;
property: string;
target: Function;
}
@Injectable()
export class LoadbalanceOrchestrator {
private readonly keyValues = new Map<string, Choose>();
constructor(
private readonly scanner: Scanner,
@InjectLoadbalance() private readonly lb: ILoadbalance,
) {
}
public addChooses(target: Function, chooses: ChooseMetadata[]) {
chooses.forEach(({ service, property }) => {
const key = `${service}__${property}__${target.constructor.name}`;
this.keyValues.set(key, { service, property, target });
});
}
public async mountChooses() {
for (const item of this.keyValues.values()) {
const { service, property, target } = item;
Object.defineProperty(target, property, {
set: (server: IServer) => {
return server;
},
get: () => {
return this.lb.choose(service);
},
});
}
}
}