-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
225 lines (189 loc) · 5.92 KB
/
index.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
var urlParser = require('urlparser');
/* default request timeout */
var DEFAULT_TIMEOUT = 5000;
/* Get browser xhr object */
var Xhr = (function() {
if(window.XDomainRequest) {
return window.XDomainRequest;
} else if(window.XMLHttpRequest) {
return window.XMLHttpRequest;
} else if(window.ActiveXObject) {
['Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.3.0','Microsoft.XMLHTTP'].forEach(function(x) {
try { return window.ActiveXObject(x); } catch (e) {}
});
throw new Error('XHR ActiveXObject failed');
}
throw new Error('XHR support not found');
}());
/* ReadyState status codes */
var XHR_CLOSED = 0,
XHR_OPENED = 1,
XHR_SENT = 2,
XHR_RECEIVED = 3,
XHR_DONE = 4;
function Ajax(method,url,options,data,res) {
var xhr = new Xhr(), headers;
if(typeof options === 'function'){
res = options;
options = null;
data = undefined;
} else if(typeof data === 'function'){
res = data;
data = undefined;
}
options = options ? options : {};
if(typeof res === 'function') {
var clb = res;
res = {
resolve: function(x){
clb(undefined,x);
},
reject: function(x,c){
clb(c||-1,x);
},
progress: function(x){
clb(0,x);
}
};
} else if(typeof res !== 'object') {
res = {
resolve: function(x){
this.result = x;
if(this.onfulfill) this.onfulfill(x);
},
reject: function(x){
this.error = x;
if(this.onreject) this.onreject(x);
},
progress: function(x){
if(this.onprogress) this.onprogress(x);
},
when: function(f,r,p){
this.onfulfill = f;
this.onreject = r;
this.onprogress = p;
},
then: this.when
};
/* must be async */
options.async = true;
} /* else resolve using res */
if(options.async === undefined) options.async = true;
if(options.timeout === undefined) options.timeout = DEFAULT_TIMEOUT;
if(!options.headers) options.headers = {};
if(options.type || !options.headers['content-type'])
options.headers['content-type'] = options.type||'application/json';
if(options.accept || !options.headers.accept)
options.headers.accept = options.accept||'application/json';
if(options.charset) options.headers['accept-charset'] = options.charset;
if("withCredentials" in xhr || XDomainRequest !== undefined) {
if(options.withCredentials === true)
xhr.withCredentials = true;
xhr.onload = function(){
res.resolve(xhr);
};
xhr.onerror = function(){
res.reject(xhr);
};
} else {
xhr.onreadystatechange = function() {
switch(xhr.readyState) {
case XHR_DONE:
if(xhr.status) res.resolve(xhr);
else res.reject(xhr); // status = 0 (timeout or Xdomain)
break;
}
};
}
/* getter for response headers */
Object.defineProperty(xhr,'headers',{
get: function(){
if(!headers) headers = parseHeaders(xhr.getAllResponseHeaders());
return headers;
}
});
/* response timeout */
if(options.timeout) {
setTimeout(function(){
xhr.abort();
}, options.timeout);
}
/* report progress */
if(xhr.upload && res.progress) {
xhr.upload.onprogress = function(e){
e.percent = e.loaded / e.total * 100;
res.progress(e);
};
}
/* parse url */
url = urlParser.parse(url);
if(!url.host) url.host = {};
/* merge host info with options */
if(!url.host.protocol && options.protocol) url.host.protocol = options.protocol;
if(!url.host.hostname && options.hostname) url.host.hostname = options.hostname;
if(!url.host.port && options.port) url.host.port = options.port;
url = url.toString();
try {
xhr.open(method,url,options.async);
} catch(error){
xhr = null;
res.reject(error);
return res;
}
/* set request headers */
Object.keys(options.headers).forEach(function(header) {
xhr.setRequestHeader(header,options.headers[header]);
});
/* stringify data */
if(data === undefined) data = null;
else if(data !== null && typeof data !== 'string' && options.headers['content-type'].match('json')){
try {
data = JSON.stringify(data);
} catch(error) {
xhr = null;
res.reject(error);
return res;
}
}
/* send http request */
try {
xhr.send(data);
/* sync mode */
if(!options.async){
if(xhr.status) res.resolve(xhr);
else res.reject(xhr);
}
} catch(error){
xhr = null;
res.reject(error);
}
return res;
}
/* Object.create polyfill */
if (!Object.create) {
Object.create = (function(){
function F(){}
return function(o){
F.prototype = o;
return new F();
};
})();
}
function parseHeaders(h) {
var ret = Object.create(null), key, val, i;
h.split('\n').forEach(function(header) {
if((i=header.indexOf(':')) > 0) {
key = header.slice(0,i).replace(/^[\s]+|[\s]+$/g,'').toLowerCase();
val = header.slice(i+1,header.length).replace(/^[\s]+|[\s]+$/g,'');
if(key && key.length) ret[key] = val;
}
});
return ret;
}
['head','get','put','post','delete','patch','trace','connect','options']
.forEach(function(method) {
Ajax[method] = function(url,options,data,res) {
return Ajax(method,url,options,data,res);
};
});
module.exports = Ajax;