-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRequestLimiter.js
93 lines (85 loc) · 1.98 KB
/
RequestLimiter.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
/**
* class Request
*/
function delay(time){
return new Promise((res) => setTimeout(res, time))
}
function Axios(args){
return new Promise((res) => {
res();
})
}
class RequestLimiter {
constructor(max = 3) {
this.maxAllowed = max;
this.pendingRequests = 0;
this.queue = [];
this.RequestTypes = ["get", "post","put","patch","delete"];
this.RequestTypes.forEach((type) => {
this[type] = this.httpRequest
})
}
incrementPending() {
this.pendingRequests++;
}
decrementPending() {
this.pendingRequests--;
}
executeNext(request) {
let isResolved = false
return new Promise((resolve) => {
setInterval(() => {
if(this.pendingRequests < this.maxAllowed && !isResolved) {
resolve(new Promise(request))
isResolved = true;
}
}, 500);
})
}
httpRequest(param) {
const args = [...arguments];
const promise = async(resolve, reject) => {
this.incrementPending();
await delay(2000)
return Axios.apply(null, args).then(res => {
console.log("resolved", param)
resolve()
this.decrementPending();
}).catch(err => {
this.decrementPending();
return err;
});
}
if(this.pendingRequests < this.maxAllowed) {
return new Promise(promise)
}else {
return this.executeNext(promise);
}
}
}
const r = new RequestLimiter();
r.get("A")
setTimeout(() => {
r.get("B");
}, 200)
setTimeout(() => {
r.get("C");
}, 500)
setTimeout(() => {
r.get("D");
}, 1000)
setTimeout(() => {
r.get("E");
}, 1200)
setTimeout(() => {
r.get("F");
}, 1500)
setTimeout(() => {
r.get("G");
}, 2000)
setTimeout(() => {
r.get("H");
}, 2000)
setTimeout(() => {
r.get("I");
}, 2100)