Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize upload timer. #372

Merged
merged 2 commits into from
Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading