brainlet/api/v1/gateway/ratelimiter.js

33 lines
956 B
JavaScript
Raw Normal View History

2020-11-26 11:42:27 +02:00
// This is "inspired" by rate-limiter-flexible
class RateLimiter {
constructor({ points=5, time=1000, minPoints=0 }) {
this.points = points;
this.minPoints = minPoints;
this.time = time;
this._flooding = {};
}
}
RateLimiter.prototype.consoom = function(discriminator) {
if (!this._flooding[discriminator]) this._flooding[discriminator] = { points: this.points, lastReset: Date.now() };
if (Math.abs(new Date() - this._flooding[discriminator].lastReset) >= this.time) {
this._flooding[discriminator] = { points: this.points, lastReset: Date.now() };
}
this._flooding[discriminator].points--;
if (this._flooding[discriminator].points <= this.minPoints) {
this._flooding[discriminator].flooding = true;
return false;
}
if (this._flooding[discriminator].flooding === true) {
return false;
}
return true;
};
module.exports = RateLimiter;