forked from MithrilJS/mithril.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.js
169 lines (151 loc) · 5.39 KB
/
request.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
"use strict"
var buildPathname = require("../pathname/build")
module.exports = function($window, Promise) {
var callbackCount = 0
var oncompletion
function makeRequest(factory) {
return function(url, args) {
if (typeof url !== "string") { args = url; url = url.url }
else if (args == null) args = {}
var promise = new Promise(function(resolve, reject) {
factory(buildPathname(url, args.params), args, function (data) {
if (typeof args.type === "function") {
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
data[i] = new args.type(data[i])
}
}
else data = new args.type(data)
}
resolve(data)
}, reject)
})
if (args.background === true) return promise
var count = 0
function complete() {
if (--count === 0 && typeof oncompletion === "function") oncompletion()
}
return wrap(promise)
function wrap(promise) {
var then = promise.then
promise.then = function() {
count++
var next = then.apply(promise, arguments)
next.then(complete, function(e) {
complete()
if (count === 0) throw e
})
return wrap(next)
}
return promise
}
}
}
function hasHeader(args, name) {
for (var key in args.headers) {
if ({}.hasOwnProperty.call(args.headers, key) && name.test(key)) return true
}
return false
}
return {
request: makeRequest(function(url, args, resolve, reject) {
var method = args.method != null ? args.method.toUpperCase() : "GET"
var body = args.body
var assumeJSON = (args.serialize == null || args.serialize === JSON.serialize) && !(body instanceof $window.FormData)
var xhr = new $window.XMLHttpRequest(),
aborted = false,
_abort = xhr.abort
xhr.abort = function abort() {
aborted = true
_abort.call(xhr)
}
xhr.open(method, url, args.async !== false, typeof args.user === "string" ? args.user : undefined, typeof args.password === "string" ? args.password : undefined)
if (assumeJSON && body != null && !hasHeader(args, /^content-type$/i)) {
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8")
}
if (typeof args.deserialize !== "function" && !hasHeader(args, /^accept$/i)) {
xhr.setRequestHeader("Accept", "application/json, text/*")
}
if (args.withCredentials) xhr.withCredentials = args.withCredentials
if (args.timeout) xhr.timeout = args.timeout
xhr.responseType = args.responseType || (typeof args.extract === "function" ? "" : "json")
for (var key in args.headers) {
if ({}.hasOwnProperty.call(args.headers, key)) {
xhr.setRequestHeader(key, args.headers[key])
}
}
if (typeof args.config === "function") xhr = args.config(xhr, args) || xhr
xhr.onreadystatechange = function() {
// Don't throw errors on xhr.abort().
if(aborted) return
if (xhr.readyState === 4) {
try {
var success = (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || (/^file:\/\//i).test(url)
// When the response type isn't "" or "text",
// `xhr.responseText` is the wrong thing to use.
// Browsers do the right thing and throw here, and we
// should honor that and do the right thing by
// preferring `xhr.response` where possible/practical.
var response = xhr.response, message
if (response == null) {
try {
response = xhr.responseText
// Note: this snippet is intentionally *after*
// `xhr.responseText` is accessed, since the
// above will throw in modern browsers (thus
// skipping the rest of this section). It's an
// IE hack to detect and work around the lack of
// native `responseType: "json"` support there.
if (typeof args.extract !== "function" && xhr.responseType === "json") response = JSON.parse(response)
}
catch (e) { response = null }
}
if (typeof args.extract === "function") {
response = args.extract(xhr, args)
success = true
} else if (typeof args.deserialize === "function") {
response = args.deserialize(response)
}
if (success) resolve(response)
else {
try { message = xhr.responseText }
catch (e) { message = response }
var error = new Error(message)
error.code = xhr.status
error.response = response
reject(error)
}
}
catch (e) {
reject(e)
}
}
}
if (body == null) xhr.send()
else if (typeof args.serialize === "function") xhr.send(args.serialize(body))
else if (body instanceof $window.FormData) xhr.send(body)
else xhr.send(JSON.stringify(body))
}),
jsonp: makeRequest(function(url, args, resolve, reject) {
var callbackName = args.callbackName || "_mithril_" + Math.round(Math.random() * 1e16) + "_" + callbackCount++
var script = $window.document.createElement("script")
$window[callbackName] = function(data) {
delete $window[callbackName]
script.parentNode.removeChild(script)
resolve(data)
}
script.onerror = function() {
delete $window[callbackName]
script.parentNode.removeChild(script)
reject(new Error("JSONP request failed"))
}
script.src = url + (url.indexOf("?") < 0 ? "?" : "&") +
encodeURIComponent(args.callbackKey || "callback") + "=" +
encodeURIComponent(callbackName)
$window.document.documentElement.appendChild(script)
}),
setCompletionCallback: function(callback) {
oncompletion = callback
},
}
}