-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.ts
77 lines (67 loc) · 2.25 KB
/
server.ts
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
import express from 'express';
import { TokenBucketRateLimiter } from './algorithms/token-bucket';
import {
FixedWindowCounterArgs,
RateLimiter,
RateLimiterArgs,
RedisSlidingWindowCounterArgs,
SlidingWindowCounterArgs,
SlidingWindowLogArgs,
TokenBucketArgs
} from './types';
import { RateLimiterType } from './enums';
import { FixedWindowCounterRateLimiter } from './algorithms/fixed-window-counter';
import { SlidingWindowLogRateLimiter } from './algorithms/sliding-window-log';
import { SlidingWindowCounterRateLimiter } from './algorithms/sliding-window-counter';
import { RedisSlidingWindowCounterRateLimiter } from './algorithms/redis-sliding-window-counter';
export const createRateLimiterServer = (
rateLimiterType: RateLimiterType,
args: RateLimiterArgs,
port: number = 8080,
debug: boolean = false
) => {
const app = express();
app.use(express.json());
app.use(express.text());
const rateLimiter = getRateLimiter(rateLimiterType, args);
app.use('/limited', (req, res, next) =>
rateLimiter.handleRequest(req, res, next)
);
app.get('/limited', (req, res) => {
res.send('Limited API endpoint\n');
});
app.get('/unlimited', (req, res) => {
res.send('Unlimited API endpoint\n');
});
const server = app.listen(port, () => {
if (debug) {
console.log('Started server on port ' + port);
}
});
// Perform cleanup
server.on('close', () => {
rateLimiter.cleanup();
});
return { server, rateLimiter };
};
function getRateLimiter(
rateLimiterType: RateLimiterType,
args: RateLimiterArgs
): RateLimiter {
switch (rateLimiterType) {
case RateLimiterType.TOKEN_BUCKET:
return new TokenBucketRateLimiter(args as TokenBucketArgs);
case RateLimiterType.FIXED_WINDOW_COUNTER:
return new FixedWindowCounterRateLimiter(args as FixedWindowCounterArgs);
case RateLimiterType.SLIDING_WINDOW_LOG:
return new SlidingWindowLogRateLimiter(args as SlidingWindowLogArgs);
case RateLimiterType.SLIDING_WINDOW_COUNTER:
return new SlidingWindowCounterRateLimiter(
args as SlidingWindowCounterArgs
);
case RateLimiterType.REDIS_SLIDING_WINDOW_COUNTER:
return new RedisSlidingWindowCounterRateLimiter(
args as RedisSlidingWindowCounterArgs
);
}
}