forked from Topener/XHR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxhr.js
418 lines (331 loc) · 11.8 KB
/
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
// Create the cache manager (a shared object)
var cacheManager = Titanium.App.Properties.getObject("cachedXHRDocuments", {});
XHR = function(){};
// Public functions
// ================
// GET
// @url (string) URL to fetch
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.get = function(url, onSuccess, onError, extraParams) {
// Debug
Titanium.API.info(url);
// Create some default params
var onSuccess = onSuccess || function(){};
var onError = onError || function(){};
var extraParams = extraParams || {};
extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
extraParams.ttl = extraParams.ttl || false;
extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
extraParams.contentType = extraParams.contentType || "application/json";
extraParams.timeout = extraParams.timeout || 30000;
var cache = readCache(url);
// If there is nothing cached, send the request
if (!extraParams.ttl || cache == 0) {
// Create the HTTP connection
var xhr = Titanium.Network.createHTTPClient({
enableKeepAlive: false,
timeout : extraParams.timeout
});
// Create the result object
var result = {};
// Open the HTTP connection
xhr.open("GET", url, extraParams.async);
xhr.setRequestHeader('Content-Type', extraParams.contentType);
// If we need to authenticate
if (extraParams.shouldAuthenticate) {
var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
xhr.setRequestHeader('Authorization', authstr);
}
// When the connection was successful
xhr.onload = function() {
// Check the status of this
result.status = xhr.status == 200 ? "ok" : xhr.status;
// Check the type of content we should serve back to the user
if (extraParams.contentType.indexOf("application/json") != -1) {
result.data = xhr.responseText;
} else if (extraParams.contentType.indexOf("text/xml") != -1) {
result.data = xhr.responseXML;
} else {
result.data = xhr.responseData;
}
onSuccess(result);
// Cache this response
writeCache(result.data, url, extraParams.ttl);
};
// When there was an error
xhr.onerror = function(e) {
// Check the status of this
result.status = "error";
result.data = e;
result.code = xhr.status;
onError(result);
};
xhr.send();
} else {
var result = {};
result.status = "cache";
result.data = cache;
onSuccess(result);
}
};
// POST requests
// @url (string) URL to fetch
// @data (object)
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.post = function(url, data, onSuccess, onError, extraParams) {
// Debug
Titanium.API.info(url + " " + JSON.stringify(data));
// Create some default params
var onSuccess = onSuccess || function(){};
var onError = onError || function(){};
var extraParams = extraParams || {};
extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
extraParams.contentType = extraParams.contentType || "application/json";
extraParams.timeout = extraParams.timeout || 30000;
// Create the HTTP connection
var xhr = Titanium.Network.createHTTPClient({
enableKeepAlive: false,
timeout : extraParams.timeout
});
// Create the result object
var result = {};
// Open the HTTP connection
xhr.open("POST", url, extraParams.async);
xhr.setRequestHeader('Content-Type', extraParams.contentType);
// If we need to authenticate
if (extraParams.shouldAuthenticate) {
var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
xhr.setRequestHeader('Authorization', authstr);
}
// When the connection was successful
xhr.onload = function() {
// Check the status of this
result.status = xhr.status == 200 ? "ok" : xhr.status;
result.data = xhr.responseText;
onSuccess(result);
};
// When there was an error
xhr.onerror = function(e) {
// Check the status of this
result.status = "error";
result.data = e.error;
result.code = xhr.status;
onError(result);
};
xhr.send(data);
};
// PUT requests
// @url (string) URL to fetch
// @data (object)
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.put = function(url, data, onSuccess, onError, extraParams) {
// Create some default params
var onSuccess = onSuccess || function(){};
var onError = onError || function(){};
var extraParams = extraParams || {};
extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
extraParams.contentType = extraParams.contentType || "application/json";
extraParams.timeout = extraParams.timeout || 30000;
// Create the HTTP connection
var xhr = Titanium.Network.createHTTPClient({
enableKeepAlive: false,
timeout : extraParams.timeout
});
// Create the result object
var result = {};
// Open the HTTP connection
xhr.open("PUT", url, extraParams.async);
xhr.setRequestHeader('Content-Type', extraParams.contentType);
// If we need to authenticate
if (extraParams.shouldAuthenticate) {
var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
xhr.setRequestHeader('Authorization', authstr);
}
// When the connection was successful
xhr.onload = function() {
// Check the status of this
result.status = xhr.status == 200 ? "ok" : xhr.status;
result.data = xhr.responseText;
onSuccess(result);
};
// When there was an error
xhr.onerror = function(e) {
// Check the status of this
result.status = "error";
result.data = e.error;
result.code = xhr.status;
onError(result);
};
xhr.send(data);
};
// DELETE requests
// @url (string) URL to fetch
// @onSuccess (function) success callback
// @onError (function) error callback
// @extraParams (object)
XHR.prototype.destroy = function(url, onSuccess, onError, extraParams) {
// Debug
Titanium.API.info(url);
// Create some default params
var onSuccess = onSuccess || function(){};
var onError = onError || function(){};
var extraParams = extraParams || {};
extraParams.async = (extraParams.hasOwnProperty('async')) ? extraParams.async : true;
extraParams.shouldAuthenticate = extraParams.shouldAuthenticate || false; // if you set this to true, pass "username" and "password" as well
extraParams.contentType = extraParams.contentType || "application/json";
extraParams.timeout = extraParams.timeout || 30000;
// Create the HTTP connection
var xhr = Titanium.Network.createHTTPClient({
enableKeepAlive: false,
timeout : extraParams.timeout
});
// Create the result object
var result = {};
// Open the HTTP connection
xhr.open("DELETE", url, extraParams.async);
xhr.setRequestHeader('Content-Type', extraParams.contentType);
// If we need to authenticate
if (extraParams.shouldAuthenticate) {
var authstr = 'Basic ' + Titanium.Utils.base64encode(extraParams.username + ':' + extraParams.password);
xhr.setRequestHeader('Authorization', authstr);
}
// When the connection was successful
xhr.onload = function() {
// Check the status of this
result.status = xhr.status == 200 ? "ok" : xhr.status;
result.data = xhr.responseText;
onSuccess(result);
};
// When there was an error
xhr.onerror = function(e) {
// Check the status of this
result.status = "error";
result.data = e.error;
result.code = xhr.status;
onError(result);
};
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();
//Titanium.API.info("REMOVED CACHE FILE " + hashedURL);
}
}
};
// 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;
//Titanium.API.info("REMOVED CACHE FILE " + cachedDocuments[i].file);
}
}
// 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;
//Titanium.API.info("REMOVED CACHE FILE " + cachedDocuments[i].file);
}
// Return the number of files deleted
return purgedDocuments;
};
// Private functions
// =================
readCache = function(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;
};
updateCacheManager = function(){
Titanium.App.Properties.setObject("cachedXHRDocuments", cacheManager);
};
writeCache = function(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;