简体   繁体   中英

Parse run a cloud code when receiving a push

I have an android application which sends a push via parse. It sends a push to a specific channel to send it's state to other devices. I want to provide multiple channels depending on the states and send each push to it's corresponding channel. I can easily do this by modifying the android code and divide the channels there. But since it is a server device, I would rather divide the channels on parse server like triggering a cloud code. Basically the server will send a push it's state and the cloud code will parse the state and push it to corresponding channel. Here's the android code:

ParsePush push = new ParsePush();
            push.setChannel("STATE_SLEEP");
            push.setMessage(message);
            push.sendInBackground();

ParsePush push = new ParsePush();
            push.setChannel("STATE_AWAKE");
            push.setMessage(message);
            push.sendInBackground();

what I want is to use this without setting the channel and let parse server decide which channel it will sent. This way I can modify or parse the message itself swell and it's easier then updating the android device.

I've send a save request from the server device first.

ParseObject notification = new ParseObject("State");
            notification.put("state", state);
            notification.saveInBackground();

And we trigger before save event in cloud code

Parse.Cloud.beforeSave("State", function(request, response) {
    var state = request.object.get("state");
    var channelExist = 0;
    for(i = 0 ; i < channels.length ; i++) {);
      // if channel exists
      push(state, channels[i], response);
    }
    push(state, "All", response);
    if(channelExist == 0) response.error("Channel not found");
});

function push(state, channel, response) {
    Parse.Push.send({
        channels: [ channel ],
        data: {
            alert: state
        }
    }, {
        success: function () {
            response.error("Push sent");
        },
        error: function (error) {
            response.error("Error sending push")
        }
    });
}

The idea to response.error in every case is to prevent saving the parse object into the core table. When the server device sends the "save to State table", cloud code triggered and send a push to corresponding channels and return an error without saving the contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM