From cfb799197f5c7702011dee58b3d48a12cd69c438 Mon Sep 17 00:00:00 2001 From: Philipp Kubler Date: Sat, 27 Jun 2015 20:01:00 +0200 Subject: [PATCH] Add getRemoteLimit to switch the limit by a route or identifies. --- Readme.md | 12 +++++++++++- lib/rate.js | 23 ++++++++++++++++++----- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/Readme.md b/Readme.md index 7c8e44f..d647fd9 100644 --- a/Readme.md +++ b/Readme.md @@ -60,7 +60,17 @@ function (req) { } ``` - A function that allows you to switch how rate identifies a route. By fefault, its the method:route_regex + A function that allows you to switch how rate identifies a route. By default, its the method:route_regex + +- *getRemoteLimit* + +```js +function (req) { + return {interval: 1, limit: 0}; +} +``` + + A function that allows you to switch the limit by a route or identifies. By default, its `null`. - *setHeaders* diff --git a/lib/rate.js b/lib/rate.js index 5a81ed1..36668d0 100644 --- a/lib/rate.js +++ b/lib/rate.js @@ -22,6 +22,10 @@ exports.defaults = function () { return req.route.method + ':' + req.route.regexp; }, + // function(req) { + // return {interval: 1, limit: 0} + // } + getRemoteLimit: null, interval: 1, @@ -82,22 +86,31 @@ exports.middleware = function recordRate(options) { var routeKey = options.getRouteKey(req), remoteKey = options.getRemoteKey(req), + limit = options.limit, + interval = options.interval, incrementCallback = null; + // check if limit function is defined + if (typeof options.getRemoteLimit === 'function') { + var remoteLimit = options.getRemoteLimit(req); + limit = remoteLimit.limit; + interval = remoteLimit.interval; + } + // check if there is a limit set on this route, and reject request with headers if so - if (options.limit) { + if (limit) { // use the callback to get the rate incrementCallback = function (rate, resetTime) { if (options.setHeaders) { - options.setHeadersHandler(req, res, rate, options.limit, resetTime); + options.setHeadersHandler(req, res, rate, limit, resetTime); } - if (rate > options.limit) { + if (rate > limit) { // we are officially over the limit - options.onLimitReached(req, res, rate, options.limit, resetTime, next); + options.onLimitReached(req, res, rate, limit, resetTime, next); } else { @@ -107,7 +120,7 @@ exports.middleware = function recordRate(options) { }; } - options.handler.increment(routeKey, remoteKey, options, next, incrementCallback); + options.handler.increment(routeKey, remoteKey, {limit: limit, interval: interval}, next, incrementCallback); // if we don't have rate limiting turned on, then we don't care when incrementing the rate finishes // let's keep going with the request