c9-core/node_modules/c9/ratelimit.js

31 wiersze
760 B
JavaScript
Czysty Zwykły widok Historia

2015-02-10 19:41:24 +00:00
var error = require("http-error");
/**
* In memory rate limiter as connect middleware
*/
module.exports = ratelimit;
function ratelimit(key, duration, max) {
2016-04-28 10:10:39 +00:00
var counts = {};
2015-02-10 19:41:24 +00:00
return function(req, res, next) {
var handle = req.params[key];
2016-04-28 10:10:39 +00:00
counts[handle] = counts[handle] || 0;
if (counts[handle] >= max) {
2015-02-10 19:41:24 +00:00
var err = new error.TooManyRequests("Rate limit exceeded");
2016-04-28 10:10:39 +00:00
err.retryIn = Math.min(duration, 5000);
return next(err);
2015-02-10 19:41:24 +00:00
}
2016-04-28 10:10:39 +00:00
counts[handle]++;
setTimeout(function () {
counts[handle]--;
if (counts[handle] == 0) {
delete counts[handle];
}
}, duration);
2015-02-10 19:41:24 +00:00
return next();
};
}