UNPKG

1.9 kBJavaScriptView Raw
1'use strict';
2module.exports = {
3 upload(request, emitter, uploadBodySize) {
4 const uploadEventFrequency = 150;
5 let uploaded = 0;
6 let progressInterval;
7
8 emitter.emit('uploadProgress', {
9 percent: 0,
10 transferred: 0,
11 total: uploadBodySize
12 });
13
14 request.once('error', () => {
15 clearInterval(progressInterval);
16 });
17
18 request.once('response', () => {
19 clearInterval(progressInterval);
20
21 emitter.emit('uploadProgress', {
22 percent: 1,
23 transferred: uploaded,
24 total: uploadBodySize
25 });
26 });
27
28 request.once('socket', socket => {
29 const onSocketConnect = () => {
30 progressInterval = setInterval(() => {
31 /* istanbul ignore next: hard to test */
32 if (socket.destroyed) {
33 clearInterval(progressInterval);
34 return;
35 }
36
37 const lastUploaded = uploaded;
38 /* istanbul ignore next: see #490 (occurs randomly!) */
39 const headersSize = request._header ? Buffer.byteLength(request._header) : 0;
40 uploaded = socket.bytesWritten - headersSize;
41
42 /* istanbul ignore next: see https://github.com/sindresorhus/got/pull/322#pullrequestreview-51647813 (no proof) */
43 if (uploadBodySize && uploaded > uploadBodySize) {
44 uploaded = uploadBodySize;
45 }
46
47 // Don't emit events with unchanged progress and
48 // prevent last event from being emitted, because
49 // it's emitted when `response` is emitted
50 if (uploaded === lastUploaded || uploaded === uploadBodySize) {
51 return;
52 }
53
54 emitter.emit('uploadProgress', {
55 percent: uploadBodySize ? uploaded / uploadBodySize : 0,
56 transferred: uploaded,
57 total: uploadBodySize
58 });
59 }, uploadEventFrequency);
60 };
61
62 if (socket.connecting) {
63 socket.once('connect', onSocketConnect);
64 } else {
65 // The socket is being reused from pool,
66 // so the connect event will not be emitted
67 onSocketConnect();
68 }
69 });
70 }
71};