Name: thunk-ratelimiter
Owner: thunks
Description: The fastest abstract rate limiter.
Created: 2015-06-13 03:08:36.0
Updated: 2018-04-03 12:24:02.0
Pushed: 2018-04-03 12:24:41.0
Size: 25
Language: JavaScript
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
The fastest abstract rate limiter.
install thunk-ratelimiter
Example Connect middleware implementation limiting against a user._id
:
t limiter = new Limiter()
ter.connect(redisClient) // connect to a thunk-redis instance
ter.get(req.user._id).then(function (limit) {
sponse.set('X-RateLimit-Limit', limit.total)
sponse.set('X-RateLimit-Remaining', limit.remaining)
sponse.set('X-RateLimit-Reset', Math.ceil(limit.reset / 1000))
all good
bug('remaining %s/%s %s', limit.remaining, limit.total, id)
(limit.remaining >= 0) return
not good
t after = Math.ceil((limit.reset - Date.now()) / 1000)
sponse.set('Retry-After', after)
sponse.end(429, 'Rate limit exceeded, retry in ' + after + ' seconds')
Return a limiter instance.
t limiter = new Limiter()
options.max
: Optional, Type: Number
, max requests within duration
, default to 2500
.options.duration
: Optional, Type: Number
, of limit in milliseconds, should greater than 100
ms, default to 3600000
.options.prefix
: Optional, Type: String
, redis key namespace, default to LIMIT
.this
this
Connect to redis. Arguments are the same as thunk-redis's createClient
, or give a thunk-redis instance.
ter.connect(6379)
Return a promise that guarantee a limiter result. it support more max
and duration
pairs ad limit policy. The first pairs will be used as default. If some trigger limit, then the limiter will apply the next pair policy.
ter.get('_userIdxxx').then(function (limit) {
nsole.log(limit)
s
ter.get('_userIdxxx:POST /files', 100, 60000, 50, 60000).then(function (limit) {
nsole.log(limit)
id
: required, Type: String
, the identifier to limit against (typically a user id)max
: Optional, Type: Number
, max requests within duration
, default to options.max
.duration
: Optional, Type: Number
, of limit in milliseconds, default to options.duration
.Result Object:
limit.remaining
- number of calls left in current duration
without decreasing current get
limit.total
- max
valuelimit.duration
- current duration
in millisecondslimit.reset
- timestamp in millisecondster.remove('_userIdxxx').then(function (res) {
nsole.log(err, res)