-
Notifications
You must be signed in to change notification settings - Fork 59
/
ti.xhr.js
453 lines (363 loc) · 13.8 KB
/
ti.xhr.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// Create the cache manager (a shared object)
var cacheManager = Ti.App.Properties.getObject("cachedXHRDocuments", {});
var storedExtraParams = addDefaultsToOptions({});
XHR = function() {};
// Public functions
// ================
// GET
// @e (object) url is required field. supports onSucces, onError and extraParams.
XHR.prototype.GET = function(e) {
return new Promise((resolve, reject) => {
// Create some default params
let onSuccess = e.onSuccess || function() {};
let onError = e.onError || function() {};
if (e.extraParams) {
var extraParams = addDefaultsToOptions(e.extraParams);
} else {
var extraParams = storedExtraParams;
}
var cache = readCache(e.url);
// If there is nothing cached, send the request
if (cache === false || !extraParams.ttl) {
var xhr = initXHRRequest('GET', e.url, extraParams);
// When the connection was successful
xhr.onload = function() {
var result = handleSuccess(xhr, extraParams);
onSuccess(result);
// only cache if there is a ttl
if (extraParams.ttl) {
writeCache(result.data, e.url, extraParams.ttl);
}
if (extraParams.promise) resolve(result);
};
// When there was an error
xhr.onerror = function(err) {
let error = handleError(xhr, err);
onError(error);
if (extraParams.promise) reject(error);
};
xhr.send();
} else {
var result = {};
result.result = "cache";
result.status = 304;
// not modified
result.data = cache;
onSuccess(result);
if (extraParams.promise) resolve(result);
}
});
};
// POST requests
// @e (object) url & data are required, supports onSuccess, onError and extraParams
XHR.prototype.POST = function(e) {
return new Promise((resolve, reject) => {
// Create some default params
var onSuccess = e.onSuccess || function() {};
var onError = e.onError || function() {};
if (e.extraParams) {
var extraParams = addDefaultsToOptions(e.extraParams);
} else {
var extraParams = storedExtraParams;
}
var xhr = initXHRRequest('POST', e.url, extraParams);
// When the connection was successful
xhr.onload = function() {
let result = handleSuccess(xhr, extraParams)
onSuccess(result);
if (extraParams.promise) resolve(result);
};
// When there was an error
xhr.onerror = function(err) {
let error = handleError(xhr, err);
onError(error);
if (extraParams.promise) reject(error);
};
xhr.send(extraParams.parseJSON ? JSON.stringify(e.data) : e.data);
});
};
// PUT requests
// @e (object) url & data are required, supports onSuccess, onError and extraParams
XHR.prototype.PUT = function(e) {
return new Promise((resolve, reject) => {
// Create some default params
var onSuccess = e.onSuccess || function() {};
var onError = e.onError || function() {};
if (e.extraParams) {
var extraParams = addDefaultsToOptions(e.extraParams);
} else {
var extraParams = storedExtraParams;
}
var xhr = initXHRRequest('PUT', e.url, extraParams);
// When the connection was successful
xhr.onload = function() {
let result = handleSuccess(xhr, extraParams);
onSuccess(result);
if (extraParams.promise) resolve(result);
};
// When there was an error
xhr.onerror = function(err) {
// Check the status of this
let error = handleError(xhr, err)
onError(error);
if (extraParams.promise) reject(error);
};
xhr.send(extraParams.parseJSON ? JSON.stringify(e.data) : e.data);
});
};
// PATCH requests
// @e (object) url & data are required, supports onSuccess, onError and extraParams
XHR.prototype.PATCH = function(e) {
return new Promise((resolve, reject) => {
// Create some default params
var onSuccess = e.onSuccess || function() {};
var onError = e.onError || function() {};
if (e.extraParams) {
var extraParams = addDefaultsToOptions(e.extraParams);
} else {
var extraParams = storedExtraParams;
}
var xhr = initXHRRequest('PATCH', e.url, extraParams);
// When the connection was successful
xhr.onload = function() {
let result = handleSuccess(xhr, extraParams);
onSuccess(result);
if (extraParams.promise) resolve(result);
};
// When there was an error
xhr.onerror = function(err) {
let error = handleError(xhr, err);
onError(error);
if (extraParams.promise) reject(error);
};
xhr.send(extraParams.parseJSON ? JSON.stringify(e.data) : e.data);
});
};
// @e (object) url is required, supports onSuccess, onError and extraParams
XHR.prototype.DELETE = function(e) {
return new Promise((resolve, reject) => {
// Create some default params
var onSuccess = e.onSuccess || function() {};
var onError = e.onError || function() {};
if (extraParams) {
var extraParams = addDefaultsToOptions(extraParams);
} else {
var extraParams = storedExtraParams;
}
var xhr = initXHRRequest('DELETE', e.url, extraParams);
// When the connection was successful
xhr.onload = function() {
let result = handleSuccess(xhr, extraParams);
onSuccess(result);
if (extraParams.promise) resolve(result);
};
// When there was an error
xhr.onerror = function(err) {
let error = handleError(xhr, err);
onError(error);
if (extraParams.promise) reject(error);
};
xhr.send();
});
};
// Helper functions
// =================
// Removes the cached content of a given URL (this is useful if you are not satisfied with the data returned that time)
XHR.prototype.clear = function(url) {
if (url) {
// Hash the URL
var hashedURL = Titanium.Utils.md5HexDigest(url);
// Check if the file exists in the manager
var cache = cacheManager[hashedURL];
// If the file was found
if (cache) {
// Delete references and file
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, hashedURL);
// Delete the record and file
delete cacheManager[hashedURL];
file.deleteFile();
// Update the cache manager
updateCacheManager();
}
}
};
// Removes all the expired documents from the manager and the file system
XHR.prototype.clean = function() {
var nowInMilliseconds = new Date().getTime();
var expiredDocuments = 0;
for (var key in cacheManager) {
var cache = cacheManager[key];
if (cache.timestamp <= nowInMilliseconds) {
// Delete references and file
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, key);
// Delete the record and file
delete cacheManager[key];
file.deleteFile();
// Update the cache manager
updateCacheManager();
// Update the deleted documents count
expiredDocuments = expiredDocuments + 1;
}
}
// Return the number of files deleted
return expiredDocuments;
};
// Removes all documents from the manager and the file system
XHR.prototype.purge = function() {
var purgedDocuments = 0;
for (var key in cacheManager) {
var cache = cacheManager[key];
// Delete references and file
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, key);
// Delete the record and file
delete cacheManager[key];
file.deleteFile();
// Update the cache manager
updateCacheManager();
// Update the deleted documents count
purgedDocuments = purgedDocuments + 1;
}
// Return the number of files deleted
return purgedDocuments;
};
XHR.prototype.setStaticOptions = function(params) {
var params = addDefaultsToOptions(params);
Ti.App.Properties.setObject("extraXHRParams", params);
storedExtraParams = params;
};
// Private Helper Functions
// ========================
function addDefaultsToOptions(providedParams) {
var extraParams = providedParams || {};
extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
extraParams.ttl = (extraParams.hasOwnProperty('ttl')) ? extraParams.ttl : false;
extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false;
extraParams.contentType = extraParams.contentType || "application/json";
extraParams.parseJSON = (extraParams.hasOwnProperty('parseJSON')) ? extraParams.parseJSON : false;
extraParams.returnXML = (extraParams.hasOwnProperty('returnXML')) ? extraParams.returnXML : false;
extraParams.debug = (extraParams.hasOwnProperty('debug')) ? extraParams.debug : false;
extraParams.requestHeaders = providedParams.requestHeaders || [];
extraParams.promise = providedParams.promise || false;
return extraParams;
}
// Return a standardized response
function handleSuccess(xhr, extraParams) {
var result = {};
result.result = "success";
result.status = xhr.status;
/**
* Check if the response is XML, if not try to parse JSON (if that was requested)
* As a final catch, when that fails too, return the data that was received;
* xhr.responseXML is null by default unless the response actually is XML
*/
try {
if (extraParams.returnXML && xhr.responseXML) {
result.data = xhr.responseXML;
} else {
result.data = extraParams.parseJSON ? JSON.parse(xhr.responseText) : xhr.responseText;
}
} catch(e) {
result.data = xhr.responseData;
}
return result;
}
// Return a standardized response
function handleError(xhr, error) {
var result = {};
result.result = "error";
result.status = xhr.status;
result.error = error.error;
// Parse error result body
try {
if (extraParams.returnXML && xhr.responseXML) {
result.data = xhr.responseXML;
} else {
result.data = extraParams.parseJSON ? JSON.parse(xhr.responseText) : xhr.responseText;
}
} catch(e) {
result.data = xhr.responseData;
}
return result;
}
function initXHRRequest(method, url, extraParams) {
// Create the HTTP connection
var xhr = Titanium.Network.createHTTPClient({
enableKeepAlive : false
});
// Open the HTTP connection
xhr.open(method, url, extraParams.async);
xhr.setRequestHeader('Content-Type', extraParams.contentType);
// add extra provided request headers
if (extraParams.requestHeaders && extraParams.requestHeaders.length > 0){
for (var i = 0; i < extraParams.requestHeaders.length; i++) {
xhr.setRequestHeader(extraParams.requestHeaders[i].key, extraParams.requestHeaders[i].value);
}
}
if (extraParams.debug) {
Ti.API.info(method + ': ' + url);
}
// If we need to authenticate
if (extraParams.shouldAuthenticate) {
if (extraParams.oAuthToken) {
var authstr = 'Bearer ' + extraParams.oAuthToken;
} else {
var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
}
xhr.setRequestHeader('Authorization', authstr);
}
return xhr;
}
// Private functions
// =================
function readCache(url) {
// Hash the URL
var hashedURL = Titanium.Utils.md5HexDigest(url);
// Check if the file exists in the manager
var cache = cacheManager[hashedURL];
// Default the return value to false
var result = false;
//Titanium.API.info("CHECKING CACHE");
// If the file was found
if (cache) {
// Fetch a reference to the cache file
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, hashedURL);
// Check that the TTL is further than the current date
if (cache.timestamp >= new Date().getTime()) {
//Titanium.API.info("CACHE FOUND");
// Return the content of the file
result = file.read();
} else {
//Titanium.API.info("OLD CACHE");
// Delete the record and file
delete cacheManager[hashedURL];
file.deleteFile();
// Update the cache manager
updateCacheManager();
}
} else {
//Titanium.API.info("CACHE " + hashedURL + " NOT FOUND");
}
return result;
};
function updateCacheManager() {
Titanium.App.Properties.setObject("cachedXHRDocuments", cacheManager);
};
function writeCache(data, url, ttl) {
//Titanium.API.info("WRITING CACHE");
// hash the url
var hashedURL = Titanium.Utils.md5HexDigest(url);
// Write the file to the disk
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, hashedURL);
// Write the file to the disk
// TODO: There appears to be a bug in Titanium and makes the method
// below always return false when dealing with binary files
file.write(data);
// Insert the cached object in the cache manager
cacheManager[hashedURL] = {
"timestamp" : (new Date().getTime()) + (ttl * 60 * 1000)
};
updateCacheManager();
//Titanium.API.info("WROTE CACHE");
};
// Return everything
module.exports = XHR;