UNPKG

ratelimit.js

Version:

A NodeJS library for efficient rate limiting using sliding windows stored in Redis.

49 lines (42 loc) 1.43 kB
// Generated by CoffeeScript 1.8.0 var ExpressMiddleware; module.exports = ExpressMiddleware = (function() { function ExpressMiddleware(rateLimiter, options) { this.rateLimiter = rateLimiter; this.options = options != null ? options : {}; } ExpressMiddleware.prototype.getIdentifiers = function(req) { return [req.ip]; }; ExpressMiddleware.prototype.weight = function(req) { return 1; }; ExpressMiddleware.prototype.middleware = function(options, callback) { var extractIps, getIdentifiers, weight, _ref; if (!callback) { _ref = [options, {}], callback = _ref[0], options = _ref[1]; } getIdentifiers = options.getIdentifiers, extractIps = options.extractIps, weight = options.weight; getIdentifiers || (getIdentifiers = extractIps); getIdentifiers || (getIdentifiers = this.getIdentifiers); weight || (weight = this.weight); return (function(_this) { return function(req, res, next) { return _this.rateLimiter.incr(getIdentifiers(req), weight(req), function(err, isLimited) { if (err) { if (_this.options.ignoreRedisErrors) { isLimited = false; } else { return next(err); } } if (isLimited) { return callback(req, res, next); } return next(); }); }; })(this); }; return ExpressMiddleware; })();