-
-
Notifications
You must be signed in to change notification settings - Fork 936
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move upload progress plumbing to its own module (#531)
- Loading branch information
1 parent
75fd8d3
commit 58c12de
Showing
2 changed files
with
71 additions
and
69 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
'use strict'; | ||
module.exports = { | ||
upload(req, emitter, uploadBodySize) { | ||
const uploadEventFrequency = 150; | ||
let uploaded = 0; | ||
let progressInterval; | ||
|
||
emitter.emit('uploadProgress', { | ||
percent: 0, | ||
transferred: 0, | ||
total: uploadBodySize | ||
}); | ||
|
||
req.once('error', () => { | ||
clearInterval(progressInterval); | ||
}); | ||
|
||
req.once('response', () => { | ||
clearInterval(progressInterval); | ||
|
||
emitter.emit('uploadProgress', { | ||
percent: 1, | ||
transferred: uploaded, | ||
total: uploadBodySize | ||
}); | ||
}); | ||
|
||
req.once('socket', socket => { | ||
const onSocketConnect = () => { | ||
progressInterval = setInterval(() => { | ||
if (socket.destroyed) { | ||
clearInterval(progressInterval); | ||
return; | ||
} | ||
|
||
const lastUploaded = uploaded; | ||
const headersSize = req._header ? Buffer.byteLength(req._header) : 0; | ||
uploaded = socket.bytesWritten - headersSize; | ||
|
||
// Prevent the known issue of `bytesWritten` being larger than body size | ||
if (uploadBodySize && uploaded > uploadBodySize) { | ||
uploaded = uploadBodySize; | ||
} | ||
|
||
// Don't emit events with unchanged progress and | ||
// prevent last event from being emitted, because | ||
// it's emitted when `response` is emitted | ||
if (uploaded === lastUploaded || uploaded === uploadBodySize) { | ||
return; | ||
} | ||
|
||
emitter.emit('uploadProgress', { | ||
percent: uploadBodySize ? uploaded / uploadBodySize : 0, | ||
transferred: uploaded, | ||
total: uploadBodySize | ||
}); | ||
}, uploadEventFrequency); | ||
}; | ||
|
||
if (socket.connecting) { | ||
socket.once('connect', onSocketConnect); | ||
} else { | ||
// The socket is being reused from pool, | ||
// so the connect event will not be emitted | ||
onSocketConnect(); | ||
} | ||
}); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters