Reputation: 4271
I have an app in Parse.com which contains 3 simple classes: User
, Alpha
, and Beta
.
User
class is populated when new users sign up for the application.Alpha
class is populated when these users create stuff (upload photos, sounds, videos, etc)Beta
class is populated when other users perform activities on objects of Alpha
class (share, favourite, etc).Task at hand:
Find a way to delete all objects in Alpha
and Beta
classes for a particular user, when they are deleted from the User
class. Right now, if a user is deleted, child objects in Alpha
and Beta
classes remain as orphan objects, and other users are still able to see these objects. This is causing inconsistencies in the application.
With my negligible understanding of the Parse backend, I think I should be using Cloud Code with Background Jobs (if I'm right), but I'm not sure how to go about it.
Upvotes: 1
Views: 260
Reputation: 62686
Before / after delete hook is the way to go, a little bit more particular advice relating to the description of the app, assuming that Alpha objects have a pointer to __User called "createdBy".
I think it's good to get in the habit of using small, promise returning functions to carry out the asynchronous steps. Something like the following...
Parse.Cloud.beforeDelete(Parse.User, function(request, response) {
var user = request.object;
deleteAlphasForUser(user).then(function(result) {
return deleteBetasForUser(user);
}).then(function(result) {
response.success(result);
}, function(error) {
response.error(error);
});
});
function deleteAlphasForUser(user) {
return alphasForUser(user).then(function(alphas) {
return Parse.Object.destroyAll(alphas);
});
}
function alphasForUser(user) {
var query = new Parse.Query("Alpha");
query.equalTo("createdBy", user);
return query.find();
}
I didn't supply deleteBetasForUser or the function that fetches betas, but they ought to be very similar to the functions for the Alpha classes.
Upvotes: 1
Reputation: 22701
CloudCode "afterDelete" triggers might be a good option. That way, the orphaned objects can be cleaned up immediately having an existing reference to the user being deleted. The link above includes a great example of a very similar solution.
Parse.Cloud.afterDelete("Post", function(request) {
query = new Parse.Query("Comment");
query.equalTo("post", request.object.id);
query.find({
success: function(comments) {
Parse.Object.destroyAll(comments, {
success: function() {},
error: function(error) {
console.error("Error deleting related comments " + error.code + ": " + error.message);
}
});
},
error: function(error) {
console.error("Error finding related comments " + error.code + ": " + error.message);
}
});
});
While a background job could work, it would have the disadvantage of having the clean up delayed until that background job is scheduled. Also, since the user was already deleted, the query for and processing of orphaned objects might be a bit inefficient.
Upvotes: 1