Browse Source

new direct middleware style

develop
Dustin Diaz 10 years ago
parent
commit
d7e38fb76a
  1. 16
      README.md
  2. 7
      index.js

16
README.md

@ -32,8 +32,8 @@ app.get('/api/action', function (req, res) {
limiter(options)
```
- `path`: `String` route path to the request
- `method`: `String` http method. accepts `get`, `post`, `put`, `delete`, and of course Express' `all`
- `path`: `String` *optional* route path to the request
- `method`: `String` *optional* http method. accepts `get`, `post`, `put`, `delete`, and of course Express' `all`
- `lookup`: `String|Array.<String>` value lookup on the request object. Can be a single value or array. See [examples](#examples) for common usages
- `total`: `Number` allowed number of requests before getting rate limited
- `expire`: `Number` amount of time in `ms` before the rate-limited is reset
@ -44,7 +44,9 @@ limiter(options)
``` js
// limit by IP address
limiter({
...
lookup: 'connection.remoteAddress'
...
})
// or if you are behind a trusted proxy (like nginx)
@ -80,7 +82,17 @@ limiter({
return !!req.user.is_admin
}
})
```
### as direct middleware
``` js
app.post('/user/update', limiter({ lookup: 'user.id' }), function (req, res) {
User.find(req.user.id).update(function (err) {
if (err) next(err)
else res.send('ok')
})
})
```
## License MIT

7
index.js

@ -1,6 +1,6 @@
module.exports = function (app, db) {
return function (opts) {
app[opts.method](opts.path, function (req, res, next) {
var middleware = function (req, res, next) {
if (opts.whitelist && opts.whitelist(req)) return next()
opts.lookup = Array.isArray(opts.lookup) ? opts.lookup : [opts.lookup]
@ -40,7 +40,8 @@ module.exports = function (app, db) {
})
})
})
}
if (opts.method && opts.path) app[opts.method](opts.path, middleware)
return middleware
}
}

Loading…
Cancel
Save