javascriptparse-serverparse-cloud-codebefore-saveafter-save

How to know if value changed in Parse Cloud Code afterSave hook?


I want to send push notifications every time the value of a single key of my object changes in a parse cloud code afterSave hook.

Parse.Cloud.afterSave("Channel", function(request) {  
    var channel = request.object
    // TODO: check if value of channel key "state" was changed
});

How can I check if the value of the key state was updated?

This is all data I can get from the request object: http://parseplatform.org/Parse-SDK-JS/api/v1.11.0/Parse.Cloud.html#.TriggerRequest

The solution suggested in this thread feels wrong: Parse Javascript API Cloud Code afterSave with access to beforeSave values

I know I can do this via the dirty method in the beforeSave hook. However this does not work for me. Why? If I do send push notifications to many users this takes some time. The clients receiving the push notifications start requesting the updated channel object from the server. However they might receive an old version of the object because as long as beforeSave has not finished sending all pushes the channel object is not persisted in the database.


Solution

  • You can use request.original. For example:

    Parse.Cloud.afterSave("Channel", function(request) {  
        var channel = request.object;
        var channel_orig = request.original;
    
        if (channel.get("status") != channel_orig.get("status")) {
            // Send push notification.
        }
    });
    

    The documentation states about request.original, that: "If set, the object, as currently stored." I'm not sure in what cases it would be set, though. In my use cases it works as provided in the code snippet above.