-
Notifications
You must be signed in to change notification settings - Fork 8
/
fetch.js
49 lines (47 loc) · 2.07 KB
/
fetch.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
import { PatchResolver } from './PatchResolver';
import { getBoundary } from './getBoundary';
export function fetchImpl(
url,
{ method, headers, credentials, body, onNext, onError, onComplete }
) {
return fetch(url, { method, headers, body, credentials })
.then((response) => {
const contentType = (!!response.headers && response.headers.get('Content-Type')) || '';
// @defer uses multipart responses to stream patches over HTTP
if (response.status < 300 && contentType.indexOf('multipart/mixed') >= 0) {
const boundary = getBoundary(contentType);
// For the majority of browsers with support for ReadableStream and TextDecoder
const reader = response.body.getReader();
const textDecoder = new TextDecoder();
const patchResolver = new PatchResolver({
onResponse: (r) => onNext(r),
boundary,
});
return reader.read().then(function sendNext({ value, done }) {
if (!done) {
let plaintext;
try {
plaintext = textDecoder.decode(value);
// Read the header to get the Content-Length
patchResolver.handleChunk(plaintext);
} catch (err) {
const parseError = err;
parseError.response = response;
parseError.statusCode = response.status;
parseError.bodyText = plaintext;
onError(parseError);
}
reader.read().then(sendNext);
} else {
onComplete();
}
});
} else {
return response.json().then((json) => {
onNext([json]);
onComplete();
});
}
})
.catch(onError);
}