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