Martin Kjellberg
Martin Kjellberg

Reputation: 615

Parse - Obj-C to Cloud Code

I'm trying to grasp Parse.com's cloud code but it is very difficult. My issue is that I want to rewrite a query which manipulates an array in cloud code (javascript)

Here is some of the code

PFQuery * quer = [PFQuery queryWithClassName:@"Spel"];
NSString * playerID = [[PFUser currentUser] objectForKey:@"fbid"];
[quer whereKey:@"lobby" containsAllObjectsInArray:@[playerID]];
[quer findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
    for (PFObject * obj in objects) {
        if (!error) {


        NSMutableArray * ready = [[obj objectForKey:@"ready"] mutableCopy];
        if (![ready containsObject:[[PFUser currentUser] objectForKey:@"fbid"]]) {
                [ready addObject:[[PFUser currentUser] objectForKey:@"fbid"]];
        }

        [obj setObject:ready forKey:@"ready"];
        [obj saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
            if (succeeded) {
            //success}

I would like to have this same code run in cloud code, since it's a multiplayer game and people click the button at the same time, there is an issue where the array is manipulated faulty.

Some kind soul out there who would know how to this? Since it feels a little more complex than just saving a normal object with cloud code

Kind Regards, Martin

Upvotes: 0

Views: 31

Answers (1)

danh
danh

Reputation: 62676

It looks like the code finds Spel objects where the current user's "fbid" is in the Spel's "lobby" array. For each one found, add the user's "fbid" to the Spel's "ready" property.

You'd say that in JS as follows:

var _ = require('underscore');

Parse.Cloud.define("myCloudFunction", function(request, response) {
    var fbid = request.user.get("fbid");
    var query = new Parse.Query("Spel");
    query.equalTo("lobby", fbid);
    query.find().then(function(results) {
        _.each(results, function(spel) {
            spel.addUnique("ready", fbid);
        });
        return Parse.Object.saveAll(results);
    }).then(function(result) {
        response.success(result);
    }, function(error) {
        response.error(error);
    });
});

Upvotes: 1

Related Questions