-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
92 lines (80 loc) · 2.25 KB
/
server.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const express = require('express');
const redis = require('redis');
const app = express();
const port = process.env.PORT || 8000;
const redisHost = process.env.REDIS_HOST;
const redisPort = process.env.REDIS_PORT || '6379';
const redisClient = redis.createClient(redisPort, redisHost);
const windowMilliseconds = 60000;
const windowMaxRequests = 5;
function getUserTokenBucket(ip) {
return new Promise((resolve, reject) => {
redisClient.hgetall(ip, function (err, tokenBucket) {
if (err) {
reject(err);
} else {
if (tokenBucket) {
tokenBucket.tokens = parseFloat(tokenBucket.tokens);
} else {
tokenBucket = { tokens: windowMaxRequests, last: Date.now() };
}
resolve(tokenBucket);
}
});
});
}
function saveUserTokenBucket(ip, tokenBucket) {
return new Promise((resolve, reject) => {
redisClient.hmset(ip, tokenBucket, function (err, response) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
function rateLimit(req, res, next) {
let userHasSufficientTokens = true;
getUserTokenBucket(req.ip)
.then((tokenBucket) => {
const timestamp = Date.now();
const elapsedMilliseconds = timestamp - tokenBucket.last;
const refreshRate = windowMaxRequests / windowMilliseconds;
tokenBucket.tokens += elapsedMilliseconds * refreshRate;
tokenBucket.tokens = Math.min(tokenBucket.tokens, windowMaxRequests);
if (tokenBucket.tokens < 1) {
userHasSufficientTokens = false;
} else {
tokenBucket.tokens -= 1;
}
tokenBucket.last = timestamp;
return saveUserTokenBucket(req.ip, tokenBucket);
})
.then(() => {
if (userHasSufficientTokens) {
next();
} else {
res.status(429).json({
error: "Too many requests per minute"
});
}
})
.catch((err) => {
next();
});
}
app.use(rateLimit);
app.get('/', function (req, res) {
res.status(200).json({
timestamp: new Date().toString()
});
});
app.use('*', function (req, res, next) {
res.status(404).json({
err: "Path " + req.originalUrl + " does not exist"
});
});
app.listen(port, function() {
console.log("== Server is running on port", port);
});