Reply to comment

Some Parse.com Cloud Code Gotchas

Getting back into CC has been full of annoying gotchas.

console.log() prints incorrectly

It stringifies the objects instead of using the formats favored by FireBug and Chrome's dev tools. So you will see things like {"foo":1} which aren't plain JS objects, but are really Parse Objects. Parse Object properties are accessed via get() and set().

Assume printed objects are really Parse Objects, which are like Backbone objects, and have a get() and set() method.

How do you get to the object that was saved?

request.object
    var game = request.object;
    board = game.get('Board');

There is no 'objectId' property.

Don't do this:

board.get('objectId')

You see {'objectId':'afeOIFej3'}, but, again, that's console.log's print messing with you.

Use the .id property instead.

console.log(board.id)

Not a gotcha, but Pointer objects need to be fetched.

A Pointer looks like this in the logs:

"Board":{"__type":"Pointer","className":"Boards","objectId":"GBt3uwmKLj"}

A Pointer is a one-to-one relationship, but it doesn't automatically retrieve the target. To load the target, you need to use .fetch().

board.fetch({ ... })

Put the code that executes after the fetch() into the success promise.

This is a newbie gotcha, but I got bit. This is wrong:

board = game.get('Board');
board.fetch();
var squares = board.get('Squares');
/// more code

When that's run, squares will be undefined. This is because board.fetch() is a slow, network operation. Yes, it's on the server, but it's still an asynchronous interaction with the database.

As with all async calls, you need to use the promises.

    board.fetch({
        success: function(board) {
            var squares = board.get('Squares');
            game.set('Score', calculate_score(squares, game.get('Moves'))); 
            game.save();
        }
    });

Reply

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options

4 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.