Browse Source

Merge pull request #7 from lennym/feature/optional-failure-callback

Allow for optional handler for rate limiting
develop
Dustin Diaz 9 years ago
parent
commit
5fbe8dc4b1
  1. 11
      README.md
  2. 6
      index.js

11
README.md

@ -47,6 +47,7 @@ limiter(options)
- `whitelist`: `function(req)` optional param allowing the ability to whitelist. return `boolean`, `true` to whitelist, `false` to passthru to limiter.
- `skipHeaders`: `Boolean` whether to skip sending HTTP headers for rate limits ()
- `ignoreErrors`: `Boolean` whether errors generated from redis should allow the middleware to call next(). Defaults to false.
- `onRateLimited`: `Function` called when a request exceeds the configured rate limit.
### Examples
@ -103,6 +104,16 @@ limiter({
skipHeaders: true
})
// call a custom limit handler
limiter({
path: '*',
method: 'all',
lookup: 'connection.remoteAddress',
onRateLimited: function (req, res, next) {
next({ message: 'Rate limit exceeded', status: 429 })
}
})
```
### as direct middleware

6
index.js

@ -3,7 +3,9 @@ module.exports = function (app, db) {
var middleware = function (req, res, next) {
if (opts.whitelist && opts.whitelist(req)) return next()
opts.lookup = Array.isArray(opts.lookup) ? opts.lookup : [opts.lookup]
opts.onRateLimited = typeof opts.onRateLimited === 'function' ? opts.onRateLimited : function (req, res, next) {
res.status(429).send('Rate limit exceeded')
}
var lookups = opts.lookup.map(function (item) {
return item + ':' + item.split('.').reduce(function (prev, cur) {
return prev[cur]
@ -41,7 +43,7 @@ module.exports = function (app, db) {
if (!opts.skipHeaders) res.set('Retry-After', after)
res.status(429).send('Rate limit exceeded')
opts.onRateLimited(req, res, next)
})
})

Loading…
Cancel
Save