-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGapiAutoBatcher.js
105 lines (81 loc) · 2.12 KB
/
GapiAutoBatcher.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
window.GapiAutoBatcher = function(config){
if(this === window){
return new GapiAutoBatcher(config);
}
config = config || {};
this.config = {};
// Make sure all configuration options have a value
for (var option in GapiAutoBatcher.defaults){
if (GapiAutoBatcher.defaults.hasOwnProperty(option)){
this.config[option] = config[option] || GapiAutoBatcher.defaults[option];
}
}
var self = this;
var batch = null;
var timeout = null;
var started = null;
var createBatch = function(){
console.log("creating a new batch");
started = Date.now()
batch = gapi.client.newBatch();
}
var delayBatch = function(){
if (timeout){
clearTimeout(timeout);
}
var delay = self.config.batchInterval;
var elapsed = Date.now() - started;
if (elapsed + delay > self.config.maxWait){
delay = self.config.maxWait - elapsed;
}
timeout = setTimeout(callBatch, delay);
}
var callBatch = function(){
batch.execute();
batch = null;
console.log("executed batch");
}
this.execute = function(request){
//Temporary fix for a big in Google's js sdk.
//TODO([email protected]): remove this as soon as I've had a reply at: https://code.google.com/p/google-api-javascript-client/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary&groupby=&sort=&id=173
request.then(function(){});
if (batch == null){
createBatch();
}
batch.add(request);
delayBatch();
return request;
}
}
window.GapiAutoBatcher.defaults = {
batchInterval: 50,
maxWait: 100
};
window.GapiAutoBatcher.gapi = {
listeners: [],
resolved: false,
then: function(f){
if(this.resolved){
f();
return;
}
this.listeners.push(f);
},
resolve: function(){
this.resolved = true;
for(var i=0; i<this.listeners.length; i++){
this.listeners[i]();
}
}
}
window.initGapi = function(){
window.GapiAutoBatcher.gapi.resolve();
}
if(window.gapi && gapi.client){
initGapi();
}
(function(global){
if(global.module){
module.exports = GapiAutoBatcher;
}
})