2
votes

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?

1
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
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

1 Answers

1
votes

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();
});