-
Notifications
You must be signed in to change notification settings - Fork 4
/
q-xhr.js
364 lines (301 loc) · 9.75 KB
/
q-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
// Currently requires polyfills for
// Array#forEach
// Object.keys
// String#trim
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['q'], function(Q) {
return factory(XMLHttpRequest, Q)
})
} else if (typeof exports === 'object' && typeof module === 'object') {
// CommonJS, mainly for testing
module.exports = factory
} else {
if (typeof Q !== 'undefined') {
factory(XMLHttpRequest, Q)
}
}
})(function(XHR, Q) {
// shallow extend with varargs
function extend(dst) {
Array.prototype.forEach.call(arguments, function(obj) {
if (obj && obj !== dst) {
Object.keys(obj).forEach(function(key) {
dst[key] = obj[key]
})
}
})
return dst
}
function lowercase(str) {
return (str || '').toLowerCase()
}
function parseHeaders(headers) {
var parsed = {}, key, val, i
if (!headers) return parsed
headers.split('\n').forEach(function(line) {
i = line.indexOf(':')
key = lowercase(line.substr(0, i).trim())
val = line.substr(i + 1).trim()
if (key) {
if (parsed[key]) {
parsed[key] += ', ' + val
} else {
parsed[key] = val
}
}
})
return parsed
}
function headersGetter(headers) {
var headersObj = typeof headers === 'object' ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers)
if (name) {
return headersObj[lowercase(name)]
}
return headersObj
}
}
function transformData(data, headers, fns) {
if (typeof fns === 'function') {
return fns(data, headers)
}
fns.forEach(function(fn) {
data = fn(data, headers)
})
return data
}
function isSuccess(status) {
return 200 <= status && status < 300
}
function forEach(obj, iterator, context) {
var keys = Object.keys(obj)
keys.forEach(function(key) {
iterator.call(context, obj[key], key)
})
return keys
}
function forEachSorted(obj, iterator, context) {
var keys = Object.keys(obj).sort()
keys.forEach(function(key) {
iterator.call(context, obj[key], key)
})
return keys
}
function buildUrl(url, params) {
if (!params) return url
var parts = []
forEachSorted(params, function(value, key) {
if (value == null) return
if (!Array.isArray(value)) value = [value]
value.forEach(function(v) {
if (typeof v === 'object') {
v = JSON.stringify(v)
}
parts.push(encodeURIComponent(key) + '=' +
encodeURIComponent(v))
})
})
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&')
}
Q.xhr = function (requestConfig) {
var defaults = Q.xhr.defaults,
config = {
transformRequest: defaults.transformRequest,
transformResponse: defaults.transformResponse
},
mergeHeaders = function(config) {
var defHeaders = defaults.headers,
reqHeaders = extend({}, config.headers),
defHeaderName, lowercaseDefHeaderName, reqHeaderName,
execHeaders = function(headers) {
forEach(headers, function(headerFn, header) {
if (typeof headerFn === 'function') {
var headerContent = headerFn()
if (headerContent != null) {
headers[header] = headerContent
} else {
delete headers[header]
}
}
})
}
defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
// execute if header value is function
execHeaders(defHeaders);
execHeaders(reqHeaders);
// using for-in instead of forEach to avoid unecessary iteration after header has been found
defaultHeadersIteration:
for (defHeaderName in defHeaders) {
lowercaseDefHeaderName = lowercase(defHeaderName);
for (reqHeaderName in reqHeaders) {
if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
continue defaultHeadersIteration;
}
}
reqHeaders[defHeaderName] = defHeaders[defHeaderName];
}
return reqHeaders;
},
headers = mergeHeaders(requestConfig)
extend(config, requestConfig)
config.headers = headers
config.method = (config.method || 'GET').toUpperCase()
var serverRequest = function(config) {
headers = config.headers
var reqData = transformData(config.data, headersGetter(headers), config.transformRequest)
// strip content-type if data is undefined TODO does it really matter?
if (config.data == null) {
forEach(headers, function(value, header) {
if (lowercase(header) === 'content-type') {
delete headers[header]
}
})
}
if (config.withCredentials == null && defaults.withCredentials != null) {
config.withCredentials = defaults.withCredentials
}
var url = buildUrl(config.url, config.params),
cache = config.cache || defaults.cache
if (cache) {
var cachedResp = cache.get(url)
if (cachedResp !== undefined) {
return Q.when(cachedResp)
}
return sendReq(url, config, reqData).then(transformResponse, transformResponse).then(function(resp) {
cache.put(url, resp)
return resp
})
} else {
return sendReq(url, config, reqData).then(transformResponse, transformResponse)
}
},
transformResponse = function(response) {
response.data = transformData(response.data, response.headers, config.transformResponse)
return isSuccess(response.status) ? response : Q.reject(response)
},
promise = Q.when(config)
// build a promise chain with request interceptors first, then the request, and response interceptors
Q.xhr.interceptors.filter(function(interceptor) {
return !!interceptor.request || !!interceptor.requestError
}).map(function(interceptor) {
return { success: interceptor.request, failure: interceptor.requestError }
})
.concat({ success: serverRequest })
.concat(Q.xhr.interceptors.filter(function(interceptor) {
return !!interceptor.response || !!interceptor.responseError
}).map(function(interceptor) {
return { success: interceptor.response, failure: interceptor.responseError }
})
).forEach(function(then) {
promise = promise.then(then.success, then.failure)
})
return promise
}
var contentTypeJson = { 'Content-Type': 'application/json;charset=utf-8' }
Q.xhr.defaults = {
transformResponse: [function(data, headers) {
if (typeof data === 'string' && data.length && (headers('content-type') || '').indexOf('json') >= 0) {
data = JSON.parse(data);
}
return data
}],
transformRequest: [function(data) {
return !!data && typeof data === 'object' && data.toString() !== '[object File]' ?
JSON.stringify(data) : data
}],
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: contentTypeJson,
put: contentTypeJson,
patch: contentTypeJson
}
}
Q.xhr.interceptors = []
Q.xhr.pendingRequests = []
function sendReq(url, config, reqData) {
var deferred = Q.defer(),
promise = deferred.promise,
aborted = -1,
xhr = new XHR(),
status,
timeoutId
Q.xhr.pendingRequests.push(config)
xhr.open(config.method, url, true)
forEach(config.headers, function(value, key) {
if (value) {
xhr.setRequestHeader(key, value)
}
})
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var response, responseHeaders
if (status !== aborted) {
responseHeaders = xhr.getAllResponseHeaders()
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
response = xhr.responseType ? xhr.response : xhr.responseText
}
// cancel timeout and subsequent timeout promise resolution
timeoutId && clearTimeout(timeoutId)
status = status || xhr.status
xhr = null
// normalize status, including accounting for IE bug (http://bugs.jquery.com/ticket/1450)
status = Math.max(status == 1223 ? 204 : status, 0)
var idx = Q.xhr.pendingRequests.indexOf(config)
if (idx !== -1) Q.xhr.pendingRequests.splice(idx, 1)
;(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(responseHeaders),
config: config
})
}
}
xhr.onprogress = function (progress) {
progress.upload = false
deferred.notify(progress)
}
if (xhr.upload && !config.disableUploadProgress) {
xhr.upload.onprogress = function (progress) {
progress.upload = true
deferred.notify(progress)
}
}
if (config.withCredentials) {
xhr.withCredentials = true
}
if (config.responseType) {
xhr.responseType = config.responseType;
}
xhr.send(reqData || null)
if (config.timeout > 0) {
timeoutId = setTimeout(function() {
status = aborted;
xhr && xhr.abort()
}, config.timeout)
}
return promise
}
['get', 'delete', 'head'].forEach(function(name) {
Q.xhr[name] = function(url, config) {
return Q.xhr(extend(config || {}, {
method: name,
url: url
}))
}
});
['post', 'put', 'patch'].forEach(function(name) {
Q.xhr[name] = function(url, data, config) {
return Q.xhr(extend(config || {}, {
method: name,
url: url,
data: data
}))
}
})
return Q
})