-
Notifications
You must be signed in to change notification settings - Fork 0
/
rye-request.js
229 lines (199 loc) · 6.18 KB
/
rye-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
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
var util = Rye.require('Util')
, manipulation = Rye.require('Manipulation')
, noop = function(){}
, escape = encodeURIComponent
, accepts = {
types : ['arraybuffer', 'blob', 'document', 'json', 'text']
, json : 'application/json'
, xml : 'application/xml, text/xml'
, html : 'text/html, application/xhtml+xml'
, text : 'text/plain'
}
, defaults = {
method : 'GET'
, url : window.location.toString()
, async : true
, accepts : accepts
, callback : noop
, timeout : 0
// , headers : {}
// , contentType : null
// , data : null
// , responseType : null
// , headers : null
}
function serialize (obj) {
var params = []
;(function fn (obj, scope) {
util.each(obj, function(value, key){
value = obj[key]
if (scope) {
key = scope + '[' + (Array.isArray(obj) ? '' : key) + ']'
}
if (util.is(['array', 'object'], value)) {
fn(value, key)
} else {
params.push(escape(key) + '=' + escape(value))
}
})
})(obj)
return params.join('&').replace(/%20/g, '+')
}
function appendQuery (url, query) {
return (url + '&' + query).replace(/[&?]+/, '?')
}
function parseData (options) {
if (options.data && (typeof options.data !== 'string')) {
options.data = serialize(options.data)
}
if (options.data && options.method === 'GET') {
options.url = appendQuery(options.url, options.data)
}
}
function parseMime (mime) {
return mime && (mime.split('/')[1] || mime)
}
function parseJSON (xhr) {
var data = xhr.response
// error of responseType: json
if (data === null) {
return new Error('Parser Error')
}
if (typeof data !== 'object') {
try {
data = JSON.parse(xhr.responseText)
} catch (err) {
return err
}
}
return data
}
function parseXML (xhr) {
var data = xhr.responseXML
// parse xml to IE 9
if (data.xml && window.DOMParser) {
try {
var parser = new window.DOMParser()
data = parser.parseFromString(data.xml, 'text/xml')
} catch (err) {
return err
}
}
return data
}
function request (options, callback) {
if (typeof options === 'string') {
options = { url: options }
}
if (!callback) {
callback = options.callback || noop
}
var settings = util.extend({}, defaults, options)
, xhr = new window.XMLHttpRequest()
, mime = settings.accepts[settings.responseType]
, abortTimeout = null
, headers = {}
settings.method = settings.method.toUpperCase()
parseData(settings)
// sets request's accept and content type
if (mime) {
headers['Accept'] = mime
if (xhr.overrideMimeType) {
xhr.overrideMimeType(mime.split(',')[0])
}
}
if (settings.contentType || ['POST', 'PUT'].indexOf(settings.method) >= 0) {
headers['Content-Type'] = settings.contentType || 'application/x-www-form-urlencoded'
}
util.extend(headers, settings.headers || {})
xhr.onreadystatechange = function(){
var err, data
if (xhr.readyState != 4 || !xhr.status) {
return
}
xhr.onreadystatechange = noop
clearTimeout(abortTimeout)
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
xhr.type = settings.responseType || xhr.responseType || parseMime(xhr.getResponseHeader('content-type'))
switch (xhr.type) {
case 'json':
data = parseJSON(xhr)
break
case 'xml':
data = parseXML(xhr)
break
default:
data = xhr.responseText
}
if (data instanceof Error) {
err = data
data = undefined
}
} else {
err = new Error('Request failed')
}
callback.call(xhr, err, data, xhr)
}
xhr.ontimeout = function(){
callback.call(xhr, new Error('Timeout'), null, xhr)
}
xhr.open(settings.method, settings.url, settings.async)
// implements fallback to request's abort by timeout
if (!('timeout' in xhr) && settings.timeout > 0) {
abortTimeout = setTimeout(function(){
xhr.onreadystatechange = noop
xhr.abort()
xhr.ontimeout()
}, settings.timeout)
}
// exports settings to xhr and sets headers
util.each(settings, function(value, key) {
if (key !== 'responseType' || accepts.types.indexOf(value) >= 0) {
try { xhr[key] = value } catch (e) {}
}
})
util.each(headers, function(value, name) {
xhr.setRequestHeader(name, value)
})
xhr.send(settings.data)
return xhr
}
function requestProxy (method, options, callback) {
if (typeof options === 'string') {
options = { url: options }
}
options.method = method
return request(options, callback)
}
var hideTypes = 'fieldset submit reset button image radio checkbox'.split(' ')
this.serialize = function () {
var form = this.get(0)
, fields = {}
, ryeForm = new Rye(form && form.elements)
ryeForm.forEach(function(field){
if (!field.disabled && (
field.checked
|| (field.type && hideTypes.indexOf(field.type) < 0)
)
) {
fields[field.name] = manipulation.getValue(field)
}
})
return serialize(fields)
}
// Exported methods
// ----------------
Rye.request = request
Rye.get = util.curry(requestProxy, 'GET')
Rye.post = util.curry(requestProxy, 'POST')
// prevents to attach properties on request
var exports = request.bind({})
util.extend(exports, {
serialize : serialize
, appendQuery : appendQuery
, defaults : defaults
, get : util.curry(requestProxy, 'GET')
, post : util.curry(requestProxy, 'POST')
// https://github.com/mlbli/craft/blob/master/src/ajax.js#L77
})
return exports