Skip to content

Commit

Permalink
optimize limiter
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidCai1111 committed May 9, 2016
1 parent 53e7ae6 commit 151823c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ npm install koa-decorators

* [@router](#router)
* [@required](#required)
* [@limiter](#limiter)

## Docs

Expand Down Expand Up @@ -102,3 +103,37 @@ module.exports = class UserController {
> curl localhost:3003/user?id=1
> user
```

### @limiter

Add rate-limiting for the decorated controller.

It accepts two arguments:
- limit: `Number`, milliseconds, the times this controller can be visited in `duration`, by default it is `10000`.
- duration: `Number`, milliseconds, by default it is `60000`.

#### Example
```js
// apis/user.js
'use strict'
const {limiter} = require('koa-decorators')

module.exports = class UserController {
@router({method: 'GET', path: '/user'})
@limiter({limit: 3, duration: 60000})
async getUserById (ctx) {
ctx.body = 'user'
}
}
```

```sh
> curl localhost:3003/user
> user
> curl localhost:3003/user
> user
> curl localhost:3003/user
> user
> curl localhost:3003/user
> Too Many Requests
```
4 changes: 4 additions & 0 deletions src/limiter.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ function handleDescriptor (target, name, descriptor, rules) {

async function middleware (ctx, next) {
let {limit, duration} = rules
if (!limit) limit = 10000
if (!duration) duration = 60000
limit += 1

let limiter = limitMapper.get(ctx.url)
let now = Date.now()

Expand Down

0 comments on commit 151823c

Please sign in to comment.