forked from volpav/batchjs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbatch.js
91 lines (77 loc) · 2.78 KB
/
batch.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
var $ = require('jquery');
/**
* Packs the given requests into the batch and returns batch contents.
* @param {Array} data Data to pack.
* @param {string} boundary Muti-part boundary mark.
*/
var pack = function (data, boundary) {
var body = [];
$.each(data, function (i, d) {
var t = d.type.toUpperCase(), noBody = ['GET', 'DELETE'], idx;
body.push('--' + boundary);
body.push('Content-Type: application/http; msgtype=request', '');
body.push(t + ' ' + d.url + ' HTTP/1.1');
/* Don't care about content type for requests that have no body. */
if (noBody.indexOf(t) < 0) {
body.push('Content-Type: ' + (d.contentType || 'application/json; charset=utf-8'));
}
body.push('Host: ' + location.host);
// add in custom headers to the batch if there are any
if (d.hasOwnProperty('headers')) {
for (idx in d.headers) {
if (!d.headers.hasOwnProperty(idx)) {
continue;
}
body.push(idx + ': ' + d.headers[idx]);
}
}
body.push('', d.data ? JSON.stringify(d.data) : '');
});
body.push('--' + boundary + '--', '');
return body.join('\r\n');
}
/**
* Unpacks the given response and passes the unpacked data to the original callback.
* @param {object} xhr jQuery XHR object.
* @param {string} status Response status.
* @param {Function} complete A callback to be executed upon unpacking the response.
*/
var unpack = function (xhr, status, complete) {
var lines = xhr.responseText.split('\r\n'),
boundary = lines[0], data = [], d = null;
$.each(lines, function (i, l) {
if (l.length) {
if (l.indexOf(boundary) == 0) {
if (d) data.push(d);
d = {};
} else if (d) {
if (!d.status) {
d.status = parseInt((function (m) {
return m || [0, 0];
})(/HTTP\/1.1 ([0-9]+)/g.exec(l))[1], 10);
} else if (!d.data) {
try {
d.data = JSON.parse(l);
} catch (ex) { }
}
}
}
});
complete.call(this, xhr, status, data);
}
module.exports = {
ajaxBatch: function (params) {
var boundary = new Date().getTime().toString();
$.ajax({
type: 'POST',
url: params.url,
dataType: 'json',
headers: params.headers,
data: pack(params.data, boundary),
contentType: 'multipart/mixed; boundary="' + boundary + '"',
complete: params.complete ?
function (xnr, status) { unpack(xnr, status, params.complete); } :
null
});
}
};