-
Notifications
You must be signed in to change notification settings - Fork 0
/
smart-hitter.js
109 lines (94 loc) · 1.96 KB
/
smart-hitter.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
class SmartHitter{
constructor(){
this.shQueue = [];
this.shRunning = [];
}
isRunning(name){
var response = false;
for(var i = 0; i<this.shRunning.length && !response; i++){
if(this.shRunning[i] == name){
response = true;
}
}
return response;
}
addToQueue(name, url, method, data){
this.shQueue.push({
name: name,
url: url,
method: method,
data: data
})
}
addToRunning(name){
this.shRunning.push(name);
}
fetchFromServer(name, url, method, data){
if(method=='POST'){
return fetch(url, {
method: 'POST',
body: JSON.stringify(data)
})
}else{
return fetch(url, {
method: 'GET'
})
}
}
removeFromRunning(name){
var response = false;
for(var i=0; i<this.shRunning.length && !response; i++){
if(this.shRunning[i]==name){
this.shRunning.splice(i, 1);
response = true
}
}
return response;
}
inQueue(name){
var response = false;
for(var i = 0; i<this.shQueue.length && !response; i++){
if(this.shQueue[i].name == name){
response = true;
}
}
return response;
}
callLatest(name){
var achieved = false;
var response = null;
for(var i = this.shQueue.length-1; i >= 0; i--){
if(this.shQueue[i].name==name){
if(!achieved){
achieved = true;
response = this.hit(this.shQueue[i].name, this.shQueue[i].url, this.shQueue[i].method, this.shQueue[i].data);
this.shQueue.splice(i, 1);
}else{
this.shQueue.splice(i, 1);
}
}
}
return response;
}
hit(name, url, method, data){
if(this.isRunning(name)){
this.addToQueue(name, url, method, data);
return new Promise(function(resolve, reject){
reject({
errorMessage: 'In Queue'
})
})
}else{
this.addToRunning(name);
return this.fetchFromServer(name, url, method, data).then((res)=>{
this.removeFromRunning(name);
if(this.inQueue(name)){
return this.callLatest(name);
}else{
return res.json();
}
});
}
}
}
export default SmartHitter;