fastify-rate-limit
Advanced tools
Comparing version 0.1.1 to 0.2.0
11
index.js
@@ -20,2 +20,3 @@ 'use strict' | ||
const max = opts.max || 1000 | ||
const whitelist = opts.whitelist || [] | ||
const timeWindow = typeof opts.timeWindow === 'string' | ||
@@ -38,7 +39,9 @@ ? ms(opts.timeWindow) | ||
var limitReached = current >= max | ||
if (limitReached === false) current++ | ||
cache.set(ip, current) | ||
res.setHeader('X-RateLimit-Limit', max) | ||
res.setHeader('X-RateLimit-Remaining', max - current) | ||
if (whitelist.indexOf(ip) === -1) { | ||
if (limitReached === false) current++ | ||
cache.set(ip, current) | ||
res.setHeader('X-RateLimit-Limit', max) | ||
res.setHeader('X-RateLimit-Remaining', max - current) | ||
} | ||
@@ -45,0 +48,0 @@ if (limitReached === false) { |
{ | ||
"name": "fastify-rate-limit", | ||
"version": "0.1.1", | ||
"version": "0.2.0", | ||
"description": "A low overhead rate limiter for your routes", | ||
@@ -25,3 +25,3 @@ "main": "index.js", | ||
"devDependencies": { | ||
"fastify": "^1.0.0-rc.2", | ||
"fastify": "^1.1.1", | ||
"standard": "^10.0.3", | ||
@@ -28,0 +28,0 @@ "tap": "^11.1.0" |
@@ -46,6 +46,7 @@ # fastify-rate-limit | ||
```js | ||
fastify.register(require('fastify-circuit-breaker'), { | ||
fastify.register(require('fastify-rate-limit'), { | ||
max: 3, // default 1000 | ||
timeWindow: 5000, // default 1000 * 60 | ||
cache: 10000 // default 5000 | ||
cache: 10000, // default 5000 | ||
whitelist: ['127.0.0.1'] // default [] | ||
}) | ||
@@ -56,2 +57,3 @@ ``` | ||
- `cache`: this plugin internally uses a lru cache to handle the clients, you can change the size of the cache with this option. | ||
- `whitelist`: array of string of ips to exlude from rate limiting | ||
@@ -58,0 +60,0 @@ <a name="license"></a> |
25
test.js
@@ -105,1 +105,26 @@ 'use strict' | ||
}) | ||
test('With ips whitelist', t => { | ||
t.plan(6) | ||
const fastify = Fastify() | ||
fastify.register(rateLimit, { max: 2, timeWindow: '2s', whitelist: ['127.0.0.1'] }) | ||
fastify.get('/', (req, reply) => { | ||
reply.send('hello!') | ||
}) | ||
fastify.inject('/', (err, res) => { | ||
t.error(err) | ||
t.strictEqual(res.statusCode, 200) | ||
fastify.inject('/', (err, res) => { | ||
t.error(err) | ||
t.strictEqual(res.statusCode, 200) | ||
fastify.inject('/', (err, res) => { | ||
t.error(err) | ||
t.strictEqual(res.statusCode, 200) | ||
}) | ||
}) | ||
}) | ||
}) |
9539
164
63