forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.js
More file actions
415 lines (377 loc) · 17.8 KB
/
http.js
File metadata and controls
415 lines (377 loc) · 17.8 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
pc.extend(pc, function () {
/**
* @name pc.Http
* @class Used to send and receive HTTP requests.
* @description Create a new Http instance. By default, a PlayCanvas application creates an instance of this
* object at `pc.http`.
*/
var Http = function Http() {
};
Http.ContentType = {
FORM_URLENCODED : "application/x-www-form-urlencoded",
GIF : "image/gif",
JPEG : "image/jpeg",
DDS : "image/dds",
JSON : "application/json",
PNG : "image/png",
TEXT : "text/plain",
XML : "application/xml",
WAV : "audio/x-wav",
OGG : "audio/ogg",
MP3 : "audio/mpeg",
MP4 : "audio/mp4",
AAC : "audio/aac",
BIN : "application/octet-stream"
};
Http.ResponseType = {
TEXT: 'text',
ARRAY_BUFFER: 'arraybuffer',
BLOB: 'blob',
DOCUMENT: 'document'
};
Http.binaryExtensions = [
'.model',
'.wav',
'.ogg',
'.mp3',
'.mp4',
'.m4a',
'.aac',
'.dds'
];
Http.prototype = {
ContentType: Http.ContentType,
ResponseType: Http.ResponseType,
binaryExtensions: Http.binaryExtensions,
/**
* @function
* @name pc.Http#get
* @description Perform an HTTP GET request to the given url.
* @param {String} url
* @param {Object} [options] Additional options
* @param {Object} [options.headers] HTTP headers to add to the request
* @param {Boolean} [options.async] Make the request asynchronously. Defaults to true.
* @param {Object} [options.cache] If false, then add a timestamp to the request to prevent caching
* @param {Boolean} [options.withCredentials] Send cookies with this request. Defaults to true.
* @param {String} [options.responseType] Override the response type
* @param {Document | Object} [options.postdata] Data to send in the body of the request.
* Some content types are handled automatically. If postdata is an XML Document, it is handled. If
* the Content-Type header is set to 'application/json' then the postdata is JSON stringified.
* Otherwise, by default, the data is sent as form-urlencoded.
* @param {Function} callback The callback used when the response has returned. Passed (err, data)
* where data is the response (format depends on response type: text, Object, ArrayBuffer, XML) and
* err is the error code.
* @example
* pc.http.get("http://example.com/", function (err, response) {
* console.log(response);
* });
*/
get: function (url, options, callback) {
if (typeof(options) === "function") {
callback = options;
options = {};
}
return this.request("GET", url, options, callback);
},
/**
* @function
* @name pc.Http#post
* @description Perform an HTTP POST request to the given url
* @param {String} url The URL to make the request to
* @param {Object} data Data to send in the body of the request.
* Some content types are handled automatically. If postdata is an XML Document, it is handled. If
* the Content-Type header is set to 'application/json' then the postdata is JSON stringified.
* Otherwise, by default, the data is sent as form-urlencoded.
* @param {Object} [options] Additional options
* @param {Object} [options.headers] HTTP headers to add to the request
* @param {Boolean} [options.async] Make the request asynchronously. Defaults to true.
* @param {Object} [options.cache] If false, then add a timestamp to the request to prevent caching
* @param {Boolean} [options.withCredentials] Send cookies with this request. Defaults to true.
* @param {String} [options.responseType] Override the response type
* @param {Function} callback The callback used when the response has returned. Passed (err, data)
* where data is the response (format depends on response type: text, Object, ArrayBuffer, XML) and
* err is the error code.
*/
post: function (url, data, options, callback) {
if (typeof(options) === "function") {
callback = options;
options = {};
}
options.postdata = data;
return this.request("POST", url, options, callback);
},
/**
* @function
* @name pc.Http#put
* @description Perform an HTTP PUT request to the given url
* @param {String} url The URL to make the request to
* @param {Document | Object} data Data to send in the body of the request.
* Some content types are handled automatically. If postdata is an XML Document, it is handled. If
* the Content-Type header is set to 'application/json' then the postdata is JSON stringified.
* Otherwise, by default, the data is sent as form-urlencoded.
* @param {Object} [options] Additional options
* @param {Object} [options.headers] HTTP headers to add to the request
* @param {Boolean} [options.async] Make the request asynchronously. Defaults to true.
* @param {Object} [options.cache] If false, then add a timestamp to the request to prevent caching
* @param {Boolean} [options.withCredentials] Send cookies with this request. Defaults to true.
* @param {String} [options.responseType] Override the response type
* @param {Function} callback The callback used when the response has returned. Passed (err, data)
* where data is the response (format depends on response type: text, Object, ArrayBuffer, XML) and
* err is the error code.
*/
put: function (url, data, options, callback) {
if (typeof(options) === "function") {
callback = options;
options = {};
}
options.postdata = data;
return this.request("PUT", url, options, callback);
},
/**
* @function
* @name pc.Http#del
* @description Perform an HTTP DELETE request to the given url
* @param {Object} url The URL to make the request to
* @param {Object} [options] Additional options
* @param {Object} [options.headers] HTTP headers to add to the request
* @param {Boolean} [options.async] Make the request asynchronously. Defaults to true.
* @param {Object} [options.cache] If false, then add a timestamp to the request to prevent caching
* @param {Boolean} [options.withCredentials] Send cookies with this request. Defaults to true.
* @param {String} [options.responseType] Override the response type
* @param {Document | Object} [options.postdata] Data to send in the body of the request.
* Some content types are handled automatically. If postdata is an XML Document, it is handled. If
* the Content-Type header is set to 'application/json' then the postdata is JSON stringified.
* Otherwise, by default, the data is sent as form-urlencoded.
* @param {Function} callback The callback used when the response has returned. Passed (err, data)
* where data is the response (format depends on response type: text, Object, ArrayBuffer, XML) and
* err is the error code.
*/
del: function (url, options, callback) {
if (typeof(options) === "function") {
callback = options;
options = {};
}
return this.request("DELETE", url, options, callback);
},
/**
* @function
* @name pc.Http#request
* @description Make a general purpose HTTP request.
* @param {String} method The HTTP method "GET", "POST", "PUT", "DELETE"
* @param {String} url The url to make the request to
* @param {Object} [options] Additional options
* @param {Object} [options.headers] HTTP headers to add to the request
* @param {Boolean} [options.async] Make the request asynchronously. Defaults to true.
* @param {Object} [options.cache] If false, then add a timestamp to the request to prevent caching
* @param {Boolean} [options.withCredentials] Send cookies with this request. Defaults to true.
* @param {String} [options.responseType] Override the response type
* @param {Document|Object} [options.postdata] Data to send in the body of the request.
* Some content types are handled automatically. If postdata is an XML Document, it is handled. If
* the Content-Type header is set to 'application/json' then the postdata is JSON stringified.
* Otherwise, by default, the data is sent as form-urlencoded.
* @param {Function} callback The callback used when the response has returned. Passed (err, data)
* where data is the response (format depends on response type: text, Object, ArrayBuffer, XML) and
* err is the error code.
*/
request: function (method, url, options, callback) {
var uri, query, timestamp, postdata, xhr;
var errored = false;
if (typeof(options) === "function") {
callback = options;
options = {};
}
// store callback
options.callback = callback;
// setup defaults
if (options.async == null) {
options.async = true;
}
if (options.headers == null) {
options.headers = {};
}
if (options.postdata != null) {
if (options.postdata instanceof Document) {
// It's an XML document, so we can send it directly.
// XMLHttpRequest will set the content type correctly.
postdata = options.postdata;
}
else if (options.postdata instanceof FormData) {
postdata = options.postdata;
}
else if (options.postdata instanceof Object) {
// Now to work out how to encode the post data based on the headers
var contentType = options.headers["Content-Type"];
// If there is no type then default to form-encoded
if(contentType === undefined) {
options.headers["Content-Type"] = Http.ContentType.FORM_URLENCODED;
contentType = options.headers["Content-Type"];
}
switch(contentType) {
case Http.ContentType.FORM_URLENCODED:
// Normal URL encoded form data
postdata = "";
var bFirstItem = true;
// Loop round each entry in the map and encode them into the post data
for (var key in options.postdata) {
if (options.postdata.hasOwnProperty(key)) {
if (bFirstItem) {
bFirstItem = false;
}
else {
postdata += "&";
}
postdata += escape(key) + "=" + escape(options.postdata[key]);
}
}
break;
default:
case Http.ContentType.JSON:
if (contentType == null) {
options.headers["Content-Type"] = Http.ContentType.JSON;
}
postdata = JSON.stringify(options.postdata);
break;
}
}
else {
postdata = options.postdata;
}
}
if (!xhr) {
xhr = new XMLHttpRequest();
}
if (options.cache === false) {
// Add timestamp to url to prevent browser caching file
timestamp = pc.time.now();
uri = new pc.URI(url);
if (!uri.query) {
uri.query = "ts=" + timestamp;
}
else {
uri.query = uri.query + "&ts=" + timestamp;
}
url = uri.toString();
}
if (options.query) {
uri = new pc.URI(url);
query = pc.extend(uri.getQuery(), options.query);
uri.setQuery(query);
url = uri.toString();
}
xhr.open(method, url, options.async);
xhr.withCredentials = options.withCredentials !== undefined ? options.withCredentials : false;
xhr.responseType = options.responseType || this._guessResponseType(url);
// Set the http headers
for (var header in options.headers) {
if (options.headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header, options.headers[header]);
}
}
xhr.onreadystatechange = function () {
this._onReadyStateChange(method, url, options, xhr);
}.bind(this);
xhr.onerror = function () {
this._onError(method, url, options, xhr);
errored = true;
}.bind(this);
try {
xhr.send(postdata);
}
catch (e) {
// DWE: Don't callback on exceptions as behaviour is inconsistent, e.g. cross-domain request errors don't throw an exception.
// Error callback should be called by xhr.onerror() callback instead.
if (!errored) {
options.error(xhr.status, xhr, e);
}
}
// Return the request object as it can be handy for blocking calls
return xhr;
},
_guessResponseType: function (url) {
var uri = new pc.URI(url);
var ext = pc.path.getExtension(uri.path);
if(Http.binaryExtensions.indexOf(ext) >= 0) {
return Http.ResponseType.ARRAY_BUFFER;
}
if (ext === ".xml") {
return Http.ResponseType.DOCUMENT;
}
return Http.ResponseType.TEXT;
},
_isBinaryContentType: function (contentType) {
var binTypes = [Http.ContentType.MP4, Http.ContentType.WAV, Http.ContentType.OGG, Http.ContentType.MP3, Http.ContentType.BIN, Http.ContentType.DDS];
if (binTypes.indexOf(contentType) >= 0) {
return true;
}
return false;
},
_onReadyStateChange: function (method, url, options, xhr) {
if (xhr.readyState === 4) {
switch (xhr.status) {
case 0: {
// If this is a local resource then continue (IOS) otherwise the request
// didn't complete, possibly an exception or attempt to do cross-domain request
if (url[0] != '/') {
this._onSuccess(method, url, options, xhr);
}
break;
}
case 200:
case 201:
case 206:
case 304: {
this._onSuccess(method, url, options, xhr);
break;
}
default: {
//options.error(xhr.status, xhr, null);
this._onError(method, url, options, xhr);
break;
}
}
}
},
_onSuccess: function (method, url, options, xhr) {
var response;
var header;
var contentType;
var parts;
header = xhr.getResponseHeader("Content-Type");
if (header) {
// Split up header into content type and parameter
parts = header.split(";");
contentType = parts[0].trim();
}
// Check the content type to see if we want to parse it
if (contentType === this.ContentType.JSON || url.split('?')[0].endsWith(".json")) {
// It's a JSON response
response = JSON.parse(xhr.responseText);
} else if (this._isBinaryContentType(contentType)) {
response = xhr.response;
} else {
if (xhr.responseType === Http.ResponseType.ARRAY_BUFFER) {
logWARNING(pc.string.format('responseType: {0} being served with Content-Type: {1}', Http.ResponseType.ARRAY_BUFFER, contentType));
response = xhr.response;
} else {
if (xhr.responseType === Http.ResponseType.DOCUMENT || contentType === this.ContentType.XML) {
// It's an XML response
response = xhr.responseXML;
} else {
// It's raw data
response = xhr.responseText;
}
}
}
options.callback(null, response);//, xhr.status, xhr);
// options.success(response, xhr.status, xhr);
},
_onError: function (method, url, options, xhr) {
options.callback(xhr.status, null);//, xhr.status, xhr);
// options.error(xhr.status, xhr, null);
}
};
return {
Http: Http,
http: new Http()
};
}());