Create Installation object from Cloud code with Pa

2019-03-30 14:06发布

问题:

As documentation says - "The JavaScript SDK does not currently support modifying Installation objects.", but what about creating these objects? is it possible to create Installation objects from cloud code?

For ex:

Parse.Cloud.define("registerForNotifications", function(request,response) {

var token = request.params.deviceToken;
var deviceType = request.params.deviceType;
var user = request.user;

var installation = new Parse.Object("Installation");
if (installation) {
    installation.set("deviceToken",token);
    ... so on..
    installation.save();
}
});

Will this work? Thank you.

回答1:

Some example:

//The following Cloud Function expects two parameters: the channel to be added to this user's installations, and the object id for the user.

//It assumes that each installation has a `Pointer <_User>` back to the original user.


//...
Parse.Cloud.define("subscribeToChannel", function(request, response) {
  var channelName = request.params.channel;
  var userId = request.params.userId;

  if (!channelName) {
    response.error("Missing parameter: channel")
    return;
  }

  if (!userId) {
    response.error("Missing parameter: userId")
    return;
  }

  // Create a Pointer to this user based on their object id
  var user = new Parse.User();
  user.id = userId;

  // Need the Master Key to update Installations
  Parse.Cloud.useMasterKey();

  // A user might have more than one Installation
  var query = new Parse.Query(Parse.Installation);
  query.equalTo("user", user); // Match Installations with a pointer to this User
  query.find({
    success: function(installations) {
      for (var i = 0; i < installations.length; ++i) {
        // Add the channel to all the installations for this user
        installations[i].addUnique("channels", channel);
      }

      // Save all the installations
      Parse.Object.saveAll(installations, {
        success: function(installations) {
          // All the installations were saved.
          response.success("All the installations were updated with this channel.");
        },
        error: function(error) {
          // An error occurred while saving one of the objects.
          console.error(error);
          response.error("An error occurred while updating this user's installations.")
        },
      });
    },
    error: function(error) {
      console.error(error);
      response.error("An error occurred while looking up this user's installations.")
    }
  });
});