kopia lustrzana https://github.com/c9/core
33 wiersze
827 B
JavaScript
33 wiersze
827 B
JavaScript
![]() |
var error = require("http-error");
|
||
|
|
||
|
/**
|
||
|
* In memory rate limiter as connect middleware
|
||
|
*/
|
||
|
module.exports = ratelimit;
|
||
|
|
||
|
function ratelimit(key, duration, max) {
|
||
|
var limit = {};
|
||
|
return function(req, res, next) {
|
||
|
var handle = req.params[key];
|
||
|
|
||
|
var lim = limit[handle] || (limit[handle] = []);
|
||
|
var now = Date.now();
|
||
|
for (var i = 0; i < lim.length; i++) {
|
||
|
if (now - lim[i] > duration) {
|
||
|
lim.splice(i, 1);
|
||
|
i--;
|
||
|
}
|
||
|
else break;
|
||
|
}
|
||
|
if (lim.length > max) {
|
||
|
var err = new error.TooManyRequests("Rate limit exceeded");
|
||
|
err.retryIn = duration - (Date.now() - lim[0]);
|
||
|
next(err);
|
||
|
return;
|
||
|
}
|
||
|
lim.push(Date.now());
|
||
|
|
||
|
return next();
|
||
|
};
|
||
|
}
|