-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
53 lines (51 loc) · 1.33 KB
/
index.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
import Progress from './Progress';
export function isFetchProgressSupported() {
return (
typeof Response !== 'undefined' && typeof ReadableStream !== 'undefined'
);
}
export default function({
defaultSize = 0,
emitDelay = 10,
onProgress = () => null,
onComplete = () => null,
onError = () => null,
}) {
return function FetchProgress(response) {
if (!isFetchProgressSupported()) {
return response;
}
const { body, headers, status } = response;
const contentLength = headers.get('content-length') || defaultSize;
const progress = new Progress(contentLength, emitDelay);
const reader = body.getReader();
const stream = new ReadableStream({
start(controller) {
function push() {
reader
.read()
.then(({ done, value }) => {
if (done) {
onComplete({});
controller.close();
return;
}
if (value) {
progress.flow(
value,
onProgress
);
}
controller.enqueue(value);
push();
})
.catch((err) => {
onError(err);
});
}
push();
},
});
return new Response(stream, { headers, status });
};
}