-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathdefaultTransportFactory.js
55 lines (49 loc) · 1.55 KB
/
defaultTransportFactory.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
import fetchRequest from './fetch';
import { makeXhrTransport } from './xhr';
// selected is used to cache the detected transport.
let selected = null;
// defaultTransportFactory selects the most appropriate transport based on the
// capabilities of the current environment.
export default function defaultTransportFactory() {
if (!selected) {
selected = detectTransport();
}
return selected;
}
function detectTransport() {
if (typeof Response !== 'undefined' && Response.prototype.hasOwnProperty("body")) {
// fetch with ReadableStream support.
return fetchRequest;
}
const mozChunked = 'moz-chunked-arraybuffer';
if (supportsXhrResponseType(mozChunked)) {
// Firefox, ArrayBuffer support.
return makeXhrTransport({
responseType: mozChunked,
responseParserFactory: function () {
return response => new Uint8Array(response);
}
});
}
// Bog-standard, expensive, text concatenation with byte encoding :(
return makeXhrTransport({
responseType: 'text',
responseParserFactory: function () {
const encoder = new TextEncoder();
let offset = 0;
return function (response) {
const chunk = response.substr(offset);
offset = response.length;
return encoder.encode(chunk, { stream: true });
}
}
});
}
function supportsXhrResponseType(type) {
try {
const tmpXhr = new XMLHttpRequest();
tmpXhr.responseType = type;
return tmpXhr.responseType === type;
} catch (e) { /* IE throws on setting responseType to an unsupported value */ }
return false;
}