2

I'm using Parse cloud code to update some counters on a user when after_delete is called on certain classes. A user has counters for subscriptions, followers and following that are incremented in the before_save for subscriptions and follows and decremented in the before_delete for the same classes.

The issue I'm running into is when a user is deleted. The after_delete function destroys all related subscriptions/follows, but this triggers an update to the (deleted) user via before_delete for subscriptions/follows. This always causes the before_delete to error out.

Perhaps I'm conceptually mixed up on the best way to accomplish this, but I can't figure out how to properly set up the following code in follow before_delete:

var fromUserPointer = follow.get("fromUser");
var toUserPointer = follow.get("toUser");

fromUserPointer.fetch().then( function(fromUser){
    // update following counter
    // if from user is already deleted, none of the rest of the promise chain is executed
}.then( function (fromUser){
    return toUserPointer.fetch();
}.then( function(toUser){
    // update followers count
}

Is there a way to determine if the fromUserPointer and toUserPointer point to a valid object short of actually performing the fetch?

toddg
  • 2,863
  • 2
  • 18
  • 33
  • Do you mean.. when a user A follows a user B, the user B has its follower count incremented. Then if the user A is deleted, the user B's follower count should be decremented? Are you using a relation or a join table? – xissburg Feb 14 '15 at 15:41
  • Yes, when a user A follows a user B, the user B has its follower count incremented AND user A has their following count incremented - this works fine. The problem only arises when trying to delete a user. I'm using a join table. – toddg Feb 14 '15 at 15:48

1 Answers1

1

Its not an error to not find the user, but by not handling the missing object case on the fetch, its being treating implicitly as an error.

So...

fromUserPointer.fetch().then(f(result) {
    // good stuff
}).then(f(result) {
    // good stuff
}).then(f(result) {
    // good stuff
}, f(error) {
    // this is good stuff too, if there's no mode of failure
    // above that would cause you to want NOT to delete, then...
    response.success();
});
danh
  • 62,181
  • 10
  • 95
  • 136
  • But how would I continue on to fetch the toUser and decrement their counter? I would still need to do this (if a user deletes their account then all of the people they were following would lose 1 follower). Could I place that code in the error block? – toddg Feb 14 '15 at 18:16
  • Ok, got it. I didn't fully understand error handling. Just return a promise that isn't rejected in the error block. – toddg Feb 14 '15 at 20:57