ian
ian

Reputation: 1002

manipulating parse.com class with cloud code

I have a random messaging app using parse.com as a backend. I am saving the messages in a class called "Messages" with the keys:

After this gets saved in my Messages class, I am using cloud code to query 3 random users and send this message to them.

My question is which is the best way to do this because I foresee errors in my current method. The current method i am using is after the user presses send I save the message to Parse.com and then I call the "send to 3 random users" cloud function, but what if my message has not been successfully saved to the parse backend before the cloud function is implemented?

  -(IBAction)send{

      PFObject *message = [PFObject objectWithClassName:@"Message"];
      [message setObject:self.messageContent forKey:@"messageBody"];
      [message setObject:[[PFUser currentUser] objectId] forKey:@"senderId"];

      [message saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
        if(error){
           //show alert with error
        }
        else{
           //everything was successful
        }
       }];



       [PFCloud callFunctionInBackground:@"sendToThreeRandomUsers" withParameters:@{} 
                                                                   block:^(NSString *result, NSError *error) {
                                                                       if (!error) {
                                                                          //cloud function was a success!
                                                                       }
                                                                    }];

  }

Basically I want to know if there is a way that whenever there is a new object in the Messages class I can say send this to 3 random users from my parse backend rather than calling it from my users device?

Or Should I just totally skip saving it to my parse backend and just send it straight to my cloud code as a parameter of the cloud function? Then save it to my backend. what if the messageBody is very big though?

So this question really isnt about code but the way to structure it.

Wish I could use Hector Ramos as a tag for this question

Upvotes: 0

Views: 284

Answers (1)

kingspeech
kingspeech

Reputation: 1836

Why don't you write a afterSave method for your Messages class. Whenever new message is saved successfully, this method (Parse.Cloud.afterSave("Messages", function(request, response) {..}) is executed and 3 random users can be selected. The API explanation is in below link;

https://parse.com/docs/cloud_code_guide#functions-onsave

Hope this helps, Regards.

Upvotes: 2

Related Questions