question

brendan avatar image
brendan asked

Writing to a dynamic Key in Cloud Script

Question from a developer:

 

I'm using Cloud Script, and I'm trying to write a value to a Key that is named dynamically, but it's not working. Using the code below, my Key is coming back as being "currentPlayerId" rather than the PlayFab ID of the actual user. How can I do this correctly?

handlers.messageToPlayer = function (args) {
  var messageGroupId = args.toPlayerId + "_messages";
  server.UpdateSharedGroupData(
    {
      "SharedGroupId": messageGroupId, "Data" :
      { 
      currentPlayerId : args.messageText
      }
    }
  );
}

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
brendan avatar image
brendan answered

This happens because in parsing the actual data update call, the Key is read as a literal. If you look in the basic Cloud Script sample (added to all new titles in the service), you'll see that UpdateInternalData is called like this:

var updateUserDataResult = server.UpdateUserInternalData({
  PlayFabId: currentPlayerId,
  Data: {
    lastLevelCompleted: level
  }
});

In that call, lastLevelCompleted isn't a string previously defined, it is the Key being written. To write to a Shared Group Data with the currentPlayerId as the Key (as in your example), you would need to generate the data section first using your dynamic keys then pass it in, like this:

handlers.messageToPlayer = function (args) {
  var messageGroupId = args.toPlayerId + "_messages";
  var dataPayload = {};
  var keyString = currentPlayerId;
  dataPayload[keyString] = args.messageText;

  server.UpdateSharedGroupData(
    {
      "SharedGroupId": messageGroupId, "Data" : dataPayload
    }
  );
}

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.