-
Notifications
You must be signed in to change notification settings - Fork 41
/
turing.net.js
369 lines (326 loc) · 9.95 KB
/
turing.net.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
365
366
367
368
369
/*!
* Turing Net
* Copyright (C) 2010-2011 Alex R. Young
* MIT Licensed
*/
/**
* The Turing Net module (Ajax).
*/
define('turing.net', ['turing.core', 'turing.dom'], function(turing) {
var net = {};
/**
* Ajax request options:
*
* - `method`: {String} HTTP method - GET, POST, etc.
* - `success`: {Function} A callback to run when a request is successful
* - `error`: {Function} A callback to run when the request fails
* - `asynchronous`: {Boolean} Defaults to asynchronous
* - `postBody`: {String} The HTTP POST body
* - `contentType`: {String} The content type of the request, default is `application/x-www-form-urlencoded`
*
*/
/**
* Removes leading and trailing whitespace.
* @param {String}
* @return {String}
*/
var trim = ''.trim
? function(s) { return s.trim(); }
: function(s) { return s.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); };
function xhr() {
if (typeof XMLHttpRequest !== 'undefined' && (window.location.protocol !== 'file:' || !window.ActiveXObject)) {
return new XMLHttpRequest();
} else {
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
}
return false;
}
function successfulRequest(request) {
return (request.status >= 200 && request.status < 300) ||
request.status == 304 ||
(request.status == 0 && request.responseText);
}
/**
* Serialize JavaScript for HTTP requests.
*
* @param {Object} object An Array or Object
* @returns {String} A string suitable for a GET or POST request
*/
net.serialize = function(object) {
if (!object) return;
if (typeof object === 'string') {
return object;
}
var results = [];
for (var key in object) {
results.push(encodeURIComponent(key) + '=' + encodeURIComponent(object[key]));
}
return results.join('&');
};
/**
* JSON.parse support can be inferred using `turing.detect('JSON.parse')`.
*/
turing.addDetectionTest('JSON.parse', function() {
return window.JSON && window.JSON.parse;
});
/**
* Parses JSON represented as a string.
*
* @param {String} string The original string
* @returns {Object} A JavaScript object
*/
net.parseJSON = function(string) {
if (typeof string !== 'string' || !string) return null;
string = trim(string);
return turing.detect('JSON.parse') ?
window.JSON.parse(string) :
(new Function('return ' + string))();
};
/**
* Parses XML represented as a string.
*
* @param {String} string The original string
* @returns {Object} A JavaScript object
*/
if (window.DOMParser) {
net.parseXML = function(text) {
return new DOMParser().parseFromString(text, 'text/xml');
};
} else {
net.parseXML = function(text) {
var xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = 'false';
xml.loadXML(text);
return xml;
};
}
/**
* Creates an Ajax request. Returns an object that can be used
* to chain calls. For example:
*
* $t.post('/post-test')
* .data({ key: 'value' })
* .end(function(res) {
* assert.equal('value', res.responseText);
* });
*
* $t.get('/get-test')
* .set('Accept', 'text/html')
* .end(function(res) {
* assert.equal('Sample text', res.responseText);
* });
*
* The available chained methods are:
*
* `set` -- set a HTTP header
* `data` -- the postBody
* `end` -- send the request over the network, and calls your callback with a `res` object
* `send` -- sends the request and calls `data`: `.send({ data: value }, function(res) { });`
*
* @param {String} The URL to call
* @param {Object} Optional settings
* @returns {Object} A chainable object for further configuration
*/
function ajax(url, options) {
var request = xhr(),
promise,
then,
response = {},
chain;
if (turing.Promise) {
promise = new turing.Promise();
}
function respondToReadyState(readyState) {
if (request.readyState == 4) {
var contentType = request.mimeType || request.getResponseHeader('content-type') || '';
response.status = request.status;
response.responseText = request.responseText;
if (/json/.test(contentType)) {
response.responseJSON = net.parseJSON(request.responseText);
} else if (/xml/.test(contentType)) {
response.responseXML = net.parseXML(request.responseText);
}
response.success = successfulRequest(request);
if (options.callback) {
return options.callback(response, request);
}
if (response.success) {
if (options.success) options.success(response, request);
if (promise) promise.resolve(response, request);
} else {
if (options.error) options.error(response, request);
if (promise) promise.reject(response, request);
}
}
}
// Set the HTTP headers
function setHeaders() {
var defaults = {
'Accept': 'text/javascript, application/json, text/html, application/xml, text/xml, */*',
'Content-Type': 'application/x-www-form-urlencoded'
};
/**
* Merge headers with defaults.
*/
for (var name in defaults) {
if (!options.headers.hasOwnProperty(name))
options.headers[name] = defaults[name];
}
for (var name in options.headers) {
request.setRequestHeader(name, options.headers[name]);
}
}
if (typeof options === 'undefined') options = {};
options.method = options.method ? options.method.toLowerCase() : 'get';
options.asynchronous = options.asynchronous || true;
options.postBody = options.postBody || '';
request.onreadystatechange = respondToReadyState;
request.open(options.method, url, options.asynchronous);
options.headers = options.headers || {};
if (options.contentType) {
options.headers['Content-Type'] = options.contentType;
}
if (typeof options.postBody !== 'string') {
// Serialize JavaScript
options.postBody = net.serialize(options.postBody);
}
setHeaders();
function send() {
try {
request.send(options.postBody);
} catch (e) {
if (options.error) {
options.error();
}
}
}
chain = {
set: function(key, value) {
options.headers[key] = value;
return chain;
},
send: function(data, callback) {
options.postBody = net.serialize(data);
options.callback = callback;
send();
return chain;
},
end: function(callback) {
options.callback = callback;
send();
return chain;
},
data: function(data) {
options.postBody = net.serialize(data);
return chain;
},
then: function() {
chain.end();
if (promise) promise.then.apply(promise, arguments);
return chain;
}
};
return chain;
}
function JSONPCallback(url, success, failure) {
var self = this;
this.url = url;
this.methodName = '__turing_jsonp_' + parseInt(new Date().getTime());
this.success = success;
this.failure = failure;
function runCallback(json) {
self.success(json);
self.teardown();
}
window[this.methodName] = runCallback;
}
JSONPCallback.prototype.run = function() {
this.scriptTag = document.createElement('script');
this.scriptTag.id = this.methodName;
this.scriptTag.src = this.url.replace('{callback}', this.methodName);
document.body.appendChild(this.scriptTag);
}
JSONPCallback.prototype.teardown = function() {
window[this.methodName] = null;
delete window[this.methodName];
if (this.scriptTag) {
document.body.removeChild(this.scriptTag);
}
}
/**
* An Ajax GET request.
*
* $t.get('/get-test')
* .set('Accept', 'text/html')
* .end(function(res) {
* assert.equal('Sample text', res.responseText);
* });
*
* @param {String} url The URL to request
* @param {Object} options The Ajax request options
* @returns {Object} A chainable object for further configuration
*/
net.get = function(url, options) {
if (typeof options === 'undefined') options = {};
options.method = 'get';
return ajax(url, options);
};
/**
* An Ajax POST request.
*
* $t.post('/post-test')
* .data({ key: 'value' })
* .end(function(res) {
* assert.equal('value', res.responseText);
* });
*
* @param {String} url The URL to request
* @param {Object} options The Ajax request options (`postBody` may come in handy here)
* @returns {Object} An object for further chaining with promises
*/
net.post = function(url, options) {
if (typeof options === 'undefined') options = {};
options.method = 'post';
return ajax(url, options);
};
/**
* A jsonp request. Example:
*
* var url = 'http://feeds.delicious.com/v1/json/';
* url += 'alex_young/javascript?callback={callback}';
*
* turing.net.jsonp(url, {
* success: function(json) {
* console.log(json);
* }
* });
*
* @param {String} url The URL to request
*/
net.jsonp = function(url, options) {
if (typeof options === 'undefined') options = {};
var callback = new JSONPCallback(url, options.success, options.failure);
callback.run();
};
/**
* The Ajax methods are mapped to the `turing` object:
*
* turing.get();
* turing.post();
* turing.json();
*
*/
turing.get = net.get;
turing.post = net.post;
turing.jsonp = net.jsonp;
net.ajax = ajax;
turing.net = net;
});