-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapi.js
307 lines (270 loc) · 8.35 KB
/
api.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
define([
"require",
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/_base/window",
"dojo/_base/xhr",
"dojo/has",
"dojo/json",
"dojo/topic",
"./util/value",
"./util/async",
"./util/generateRandomUuid",
"dojo/Deferred",
"dojo/promise/all",
], function(require, declare, lang, window, request, has, json, topic, value, async,
generateRandomUuid, Deferred, whenAll) {
var ApiError = declare(Error, {
constructor: function(errorData) {
this.name = "ApiError";
this.type = errorData.name;
this.message = errorData.message || "(no details)";
this.error = errorData;
},
// toString: function() {
// return 'ApiError "'+this.name+'": '+this.message;
// },
// toLocaleString: function() {
// return this.toString();
// // return 'ApiError "'+this.name+'": '+this.message;
// },
declaredClass: "ApiError"
});
var self = {
/**
* @type {string} Default URL, if not given in params
*/
url: '/api',
/**
* @type {Object} Common parameters which are added automatically to every request
*/
requestCommonParams: {},
/**
* @type {string} Name of topic to publish events to. First arg is a boolean telling whether an XHR is active
*/
noticeTopic: 'jig/api/request',
/**
* Whether to show exceptions to the user
*
* @type {boolean}
*/
showExceptions: false,
/**
* Number of seconds between pings, when no API request is made during that time
*/
pingDelay: 300,
/**
* Delay in milliseconds of extra-time to wait before sending the XHR
*
* (used for debugging)
*
* Set to null to disable the grouping of API requests
*/
timeout: 0,
/**
* Limit upon the number of API calls per XHR
*
* If more API calls are made within the timeout, several XHR will be made
*
* @type {number}
*/
maxReqsPerXHR: 40,
/**
* Delay between different XHR made because of maxReqsPerXHR
*/
subsequentXHRDelay: 400,
/**
* Parallel requests deferred to later execution
*
* @type {Object}
*/
_deferredRequests: {},
/**
* @type {dojo/Deferred} Global XHR promise for pending XHR call
*/
_deferred: null,
/**
* Make API request - asynchronous
*
* @param {Object} req Request object
* @param {?Object} object for parameters to pass to dojo XHR.
* @return {dojo/Deferred} promise, resolved with response
*/
request: function(req, options) {
self.cancelPing();
options = options || {};
var ret = req.promise = new Deferred();
ret._request = req;
ret.whenSealed = new Deferred();
topic.publish(this.noticeTopic, { request: req, options: options });
if (options) {
req.__options = options;
}
self._deferredRequests[generateRandomUuid()] = req;
var executeRequests = function() {
// execute all deferred requests
self._timeout = null;
var reqs = lang.mixin({}, self._deferredRequests);
self._deferredRequests = {};
var _deferred = self._deferred;
// Take maxReqsPerXHR into account by dividing API calls into groups
var blocks = Object.keys(reqs).reduce(function(blocks, currentKey, idx) {
var lastObj = blocks[blocks.length - 1];
if (!lastObj || Object.keys(lastObj).length >= self.maxReqsPerXHR) {
blocks.push(lastObj = {});
}
lastObj[currentKey] = reqs[currentKey];
return blocks;
}, []);
if (blocks.length > 1) {
console.info("API: got", Object.keys(reqs).length, "calls, devided into", blocks.length, "XHR");
}
// Call self._doRequest() for actual XHR
whenAll(blocks.map(function(block, idx) {
return async.whenTimeout(idx * self.subsequentXHRDelay)
.then(function() { return self._doRequest(block, options); });
})).then(function() { _deferred.resolve(); });
};
if (!self._timeout) { // order requests, if none is pending through setTimeout()
self._deferred = new Deferred();
if (self.timeout === null) {
executeRequests();
} else {
self._timeout = window.global.setTimeout(executeRequests, self.timeout);
}
}
return ret;
},
/**
* Execute XHR for all deferred requests
*
* @return {dojo/Deferred} from XHR call
*/
_doRequest: function(req, options) {
/**
* Process single-request response
*/
var _processResponseReq =
function(req, response) {
var options = req.__options || {};
if (response.error) {
if (response.exception) {
console.info("API exception:", response.exception.message);
if (response.exception.previous) {
console.info("API previous exception:", response.exception.previous.message);
}
}
req.promise.reject(new ApiError(response.error));
return;
}
req.promise.resolve(response);
};
/**
* Process XHR (transport) response
*/
var _processResponse = function(text, xhr) {
//console.log('JiG API Response', xhr, text);
// topic.publish('noticeTopic', false);
var i, data = null;
try {
data = json.parse(text);
}
catch (e) {
console.error('JiG API response: invalid JSON string: ',
text, xhr);
for (i in req) {
if (req.hasOwnProperty(i)) {
req[i].promise.reject(new ApiError({
name: "transport:failed",
message: "invalid JSON"
}));
}
}
return;
}
// check if one req or many in the structure
if (typeof req.callback === 'function') {
_processResponseReq(req, data, xhr);
} else {
for (i in data) {
if (data.hasOwnProperty(i)) {
_processResponseReq(req[i], data[i], xhr);
}
}
}
self.delayPing();
};
/**
* Process XHR (transport) failure
*/
var _processError = function(error, xhr) {
console.error('JiG API transport Error: ', error, xhr);
for (var i in req) {
if (req.hasOwnProperty(i)) {
req[i].promise.reject(new ApiError({name: "transport:failed"}));
}
}
};
/**
* Make single request structure out of single request params
*
* @param {Object} origRequest
* @return {Object} the structure ready to be serialized
*/
var _prepareRequest = function(origRequest) {
origRequest.promise.whenSealed.resolve(origRequest);
var ret = lang.mixin({}, origRequest, self.requestCommonParams);
delete ret.promise;
delete ret.__options;
return ret;
};
var requestToSend;
if (request.module) {
requestToSend = _prepareRequest(req);
} else {
requestToSend = {};
for (var i in req) {
if (req.hasOwnProperty(i)) {
requestToSend[i] = _prepareRequest(req[i]);
}
}
}
if (has("geonef-debug")) {
try {
var jsonText = json.stringify(requestToSend);
} catch (error) {
console.error("error when stringifying object:", requestToSend);
throw error;
}
} else {
var jsonText = json.stringify(requestToSend);
}
return request.post(lang.mixin({
url: options.url || self.url,
handleAs: 'text',
postData: jsonText,
}, options), true)
.then(_processResponse, _processError);
},
/**
* Send a dumb API request to preserve the session (timed-out)
*
* Called after an effective API request has been sent.
* The timeout cleared before an API request is sent.
*/
delayPing: function() {
var delay = self.pingDelay * 1000;
self._pingTO = window.global.setTimeout(self.doPing, delay);
},
cancelPing: function() {
if (self._pingTO) {
window.global.clearTimeout(self._pingTO);
delete self._pingTO;
}
},
doPing: function() {
self.request({ module: 'user', action: 'ping' } );
},
};
return self;
});