Skip to content

Commit

Permalink
Merge pull request #372 from RomanBurunkov/master
Browse files Browse the repository at this point in the history
Optimize upload timer.
  • Loading branch information
RomanBurunkov committed Mar 14, 2024
2 parents 4313856 + 4cdd94a commit 3325e62
Show file tree
Hide file tree
Showing 5 changed files with 348 additions and 209 deletions.
2 changes: 1 addition & 1 deletion lib/processMultipart.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ module.exports = (options, req, res, next) => {
});

file.on('data', (data) => {
uploadTimer.set(); // Refresh upload timer each time new data chunk came.
uploadTimer.refresh(); // Refresh upload timer each time new data chunk came.
dataHandler(data); // Handle new piece of data.
});

Expand Down
39 changes: 30 additions & 9 deletions lib/uploadtimer.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,45 @@
class UploadTimer {
/**
* @constructor
* @param {number} timeout - timer timeout in msecs.
* @param {number} timeout - timer timeout in msecs.
* @param {Function} callback - callback to run when timeout reached.
*/
constructor(timeout = 0, callback = () => {}) {
this.timeout = timeout;
this.callback = callback;
constructor(timeout, callback) {
this.timeout = timeout || 0;
this.callback = callback || (() => {});
this.timer = null;
}

/**
* Sets the timer.
* Initializes & starts the timer.
* @returns {boolean} True if timer has been set.
*/
set() {
if (this.timer || !this.timeout) return false;
this.timer = setTimeout(() => {
this.clear();
this.callback();
}, this.timeout);
return true;
}

/**
* Clears the timer.
* If timer cleared, it has to be re-initialized again with set method.
*/
clear() {
clearTimeout(this.timer);
}

set() {
// Do not start a timer if zero timeout or it hasn't been set.
if (!this.timeout) return false;
this.clear();
this.timer = setTimeout(this.callback, this.timeout);
/**
* Refreshes timer.
* @returns {boolean} True if timer has been refreshed.
*/
refresh() {
// Do nothing if zero/empty timeout or timer hasn't been initialized.
if (!this.timer) return false;
this.timer.refresh();
return true;
}
}
Expand Down

0 comments on commit 3325e62

Please sign in to comment.