Home

Awesome

toa-ratelimit

Smart rate limiter module for toa.

NPM version Build Status Downloads

Requirements

Installation

npm install toa-ratelimit

Example

const Toa = require('toa')
const ratelimit = require('toa-ratelimit')

const app = new Toa()
app.use(ratelimit({
  redis: 6379,
  duration: 10000,
  getId: function () { return this.ip },
  policy: {
    'GET': [3, 5000],
    'GET /test': [3, 5000, 3, 10000],
    '/test': 5
  }
}))
app.use(function () {
  this.body = this.res._headers
})

app.listen(3000, () => console.log('listening on port 3000'))

API

const ratelimit = require('toa-ratelimit')

limiter is a thunk function. It can be used as middleware or module.

Use as a module:

const limiter = ratelimit({
  redis: 6379,
  duration: 10000,
  getId: function () { return this.ip },
  policy: {
    'GET': [3, 5000],
    'POST': [3, 5000, 3, 10000]
  }
})

const app = new Toa()
app.use(function * () {
  // ...
  // Used ratelimit only for `/api/test`:
  if (this.path === '/api/test') yield limiter
})

limiter.remove(context)

Remove context's rate limit data. Return thunk function.

limiter.remove(this).then(function (res) {
  console.log(res) //  1
})

Responses

Example 200 with header fields:

HTTP/1.1 200 OK

Connection:keep-alive
Content-Length:111
Content-Type:application/json; charset=utf-8
Date:Thu, 10 Dec 2015 13:21:55 GMT
X-Powered-By:Toa
X-RateLimit-Limit:3
X-RateLimit-Remaining:2
X-RateLimit-Reset:1449753721

Example 429 with header fields:

HTTP/1.1 429 Too Many Requests

Connection:keep-alive
Content-Length:39
Content-Type:text/html; charset=utf-8
Date:Thu, 10 Dec 2015 13:22:36 GMT
Retry-After:3
X-Powered-By:Toa
X-RateLimit-Limit:3
X-RateLimit-Remaining:-1
X-RateLimit-Reset:1449753759