rjweb-server
Version:
Easy and Robust Way to create a Web Server with Many Easy-to-use Features in NodeJS
30 lines (29 loc) • 852 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class Throttler {
constructor(bytes) {
this.sent = 0;
this.lastSent = Date.now();
this.bytes = bytes;
}
/**
* Insert Data into the Throttler and wait for it to be sent
* @since 9.0.0
*/ async insert(data) {
const now = Date.now();
if (now - this.lastSent >= 1000) {
this.sent = data.byteLength;
this.lastSent = now;
}
else {
if (this.sent + data.byteLength > this.bytes) {
await new Promise((resolve) => setTimeout(resolve, 1000 - (now - this.lastSent)));
this.sent = data.byteLength;
}
else {
this.sent += data.byteLength;
}
}
}
}
exports.default = Throttler;