I work on a form where my user upload files to S3. If the user leave the form without validating it, even if files are uploaded, the files upload should be canceled and the files deleted from S3.
I have no trouble deleting the files from my S3 bucket. However, I need to be able to delete them before the user leaves the current route (i.e. page) and skip it if the next route is the same page (i.e. a page refresh).
This is an issue very similar to this one on Github where they say that, basically, it can't be done. Several other similar questions are in SO too, but none offers a satisfying answer.
I wanted to check if it is possible here, since it seems to me that this is a vital feature and I expect that other people may have dealt with it before.
If it can't be done, what workaround would you advise?
I discovered a great trick to detect when the user leave the current page. Here is the recipe:
Attach a subscription (even if empty) to your route controller. This way, route loaded
= subscription active
and route left
= subscription stopped
Add an onStop()
function and put inside it all the server side code you need to execute when the user leave the page. here is how my publication looks (I delete uploaded files when the related form hasn't been submitted when page is left):
Meteor.publish("files", function(sessionId) {
var self = this;
// Here I clean all the files I need to remove because the user has
// not submitted the current form.
self.onStop(function () {
console.log (sessionId + " is cleaning...");
cleanFiles(sessionId)
});
// I look for files related to the current upload session only
if(Users.isInRoles(this.userId, ["user"])) {
return Files.find({"session_id":sessionId, "owner":this.userId}, {});
}
//and I make my publication available in case the if statement failed
return self.ready();
});
Bottom line: as far as I know, it works like a charm. This is a great way to keep track of the user activity and execute code once he leaves the page or a sub-page (whatever template route we attached the subscription to).