@duongtrungnguyen/nestro
Version:
Service registry for Nest JS
39 lines • 1.04 kB
JavaScript
class WeightedRoundRobinStrategy {
constructor() {
this.counters = /* @__PURE__ */ new Map();
this.defaultWeight = 1;
}
selectInstance(instances) {
if (!instances || instances.length === 0) {
return null;
}
if (instances.length === 1) {
return instances[0];
}
const serviceName = instances[0].name;
let totalWeight = 0;
const weights = instances.map((instance) => {
const weight = instance.metadata?.weight || this.defaultWeight;
totalWeight += weight;
return weight;
});
let counter = this.counters.get(serviceName) || 0;
counter = (counter + 1) % totalWeight;
this.counters.set(serviceName, counter);
let weightSum = 0;
for (let i = 0; i < instances.length; i++) {
weightSum += weights[i];
if (counter < weightSum) {
return instances[i];
}
}
return instances[0];
}
reset() {
this.counters.clear();
}
}
export {
WeightedRoundRobinStrategy
};
//# sourceMappingURL=weighted-round-robin.strategy.js.map