forked from juliendangers/express-limiter2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (62 loc) · 2.32 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
module.exports = function (db, app) {
var defaultKeyGen = function (req, path, method, lookup) {
return 'ratelimit:' + path + ':' + method + ':' + lookup.map(function (item) {
return item + ':' + item.split('.').reduce(function (prev, cur) {
return prev[cur];
}, req);
}).join(':');
};
return function (opts) {
var middleware = function (req, res, next) {
if (opts.whitelist && opts.whitelist(req)) {
return next();
}
opts.onRateLimited = typeof opts.onRateLimited === 'function' ? opts.onRateLimited : function (req, res, next) {
res.status(429).send('Rate limit exceeded');
};
opts.keyGenerator = typeof opts.keyGenerator === 'function' ? opts.keyGenerator : function(req) {
opts.lookup = Array.isArray(opts.lookup) ? opts.lookup : [opts.lookup];
opts.method = (opts.method || req.method).toLowerCase();
opts.path = opts.path || req.path;
return defaultKeyGen(req, opts.path, opts.method, opts.lookup);
};
var key = opts.keyGenerator(req);
db.get(key, function (err, limit) {
if (err && opts.ignoreErrors) {
return next();
}
var now = Date.now();
limit = limit ? JSON.parse(limit) : {
total: opts.total,
remaining: opts.total,
reset: now + opts.expire
};
if (now > limit.reset) {
limit.reset = now + opts.expire;
limit.remaining = opts.total;
}
// do not allow negative remaining
limit.remaining = Math.max(Number(limit.remaining) - 1, -1);
db.set(key, JSON.stringify(limit), 'PX', opts.expire, function () {
if (!opts.skipHeaders) {
res.set('X-RateLimit-Limit', limit.total);
res.set('X-RateLimit-Remaining', Math.max(limit.remaining, 0));
res.set('X-RateLimit-Reset', Math.ceil(limit.reset / 1000)); // UTC epoch seconds
}
if (limit.remaining >= 0) {
return next();
}
var after = (limit.reset - Date.now()) / 1000;
if (!opts.skipHeaders) {
res.set('Retry-After', after);
}
opts.onRateLimited(req, res, next);
});
});
};
if (app) {
app[opts.method](opts.path, middleware);
}
return middleware;
};
};