Read and write Amazon DynamoDB tables from Amazon GameSparks - GameSparks

Amazon GameSparks is currently in preview. Changes might be made to this service and to this documentation. We don't recommend using this service for production workloads.

Read and write Amazon DynamoDB tables from Amazon GameSparks

Amazon DynamoDB tables are useful for storing global game data such as level maps and catalogs. In some cases, you can also use these tables to manage match data, for example, when two or more players are competing.

This topic demonstrates how to create a DynamoDB table for in-game weapons. It also shows how to use cloud code messages to enable your game client to read and write the data.

Note

If you're new to Amazon GameSparks, we recommend that you begin with Getting started using Amazon GameSparks and Using messages to implement game logic in Amazon GameSparks.

Deploy your game for the first time

If your game is new and you've never deployed it, follow these steps.

To deploy your game for the first time
  1. In the GameSparks console, choose the name of your game.

  2. In the navigation pane, choose Dev.

  3. On the Dev page, under Snapshot, choose Deploy as new snapshot.

  4. In the Deploy as new snapshot dialog box, optionally enter a description, and then choose Save.

Create a DynamoDB table

Create a DynamoDB table named Weapons with a partition key named Name.

To create the Weapons table
  1. In the GameSparks console, choose the name of your game.

  2. Make note of the current AWS Region selected in the upper-right corner of the console.

  3. Open the Tables page of the DynamoDB console.

  4. Make sure that the Region in the upper-right corner of the DynamoDB console matches the Region of your game.

  5. Choose Create table.

  6. On the Create table page, under Table details, do the following:

    1. For Table name, enter Weapons.

    2. For Partition key, enter Name.

  7. Choose Create table.

    On the Tables page, wait for the Status of your new table to become Active.

  8. Choose the name of your table (Weapons).

  9. On the Overview tab, under General information, expand Additional info, and then copy the table's Amazon Resource Name (ARN). You need this in the next section.

An Amazon Resource Name (ARN) is a string that uniquely identifies a resource such as a game, a stage, a Lambda function, or a DynamoDB table. For more information, see Amazon Resource Names (ARNs) in the AWS General Reference.

Give your game permission to access your table

Before your GameSparks game can access your DynamoDB table, you must grant permission using AWS Identity and Access Management (IAM) policies. Create two policies: one to read from the table, and one to write to the table. Then, attach the policies to your Dev stage IAM role.

Tip

We recommend that you group sets of permissions that have the same or similar intent into separate policies, as in the following policies. It's a best practice to grant an IAM identity only the permissions that it requires to perform its functions.

To create your IAM policies
  1. Open the IAM Create policy page.

  2. Choose the JSON tab.

  3. Replace the existing JSON policy with the following policy.

    { "Version": "2012-10-17", "Statement": [ { "Action": [ "dynamodb:GetItem", "dynamodb:Query" ], "Resource": "arn:aws:dynamodb:us-east-1:111122223333:table/Weapons", "Effect": "Allow" } ] }
    Important

    Replace the value of Resource with the ARN that you copied in the previous section.

  4. Choose Next: Tags, and then choose Next: Review.

  5. On the Review policy page, do the following:

    1. For Name, enter ReadWeapons.

    2. (Optional) Enter a Description.

    3. Choose Create policy.

  6. Repeat the previous steps to create another IAM policy. For this one, use the following policy.

    { "Version": "2012-10-17", "Statement": [ { "Action": [ "dynamodb:DeleteItem", "dynamodb:PutItem", "dynamodb:UpdateItem" ], "Resource": "arn:aws:dynamodb:us-east-1:111122223333:table/Weapons", "Effect": "Allow" } ] }
    Important

    Replace the value of Resource with the ARN that you copied in the previous section.

  7. Choose Next: Tags, and then choose Next: Review.

  8. On the Review policy page, do the following:

    1. For Name, enter WriteWeapons.

    2. (Optional) Enter a Description.

    3. Choose Create policy.

To attach your IAM policies
  1. In the GameSparks console, choose the name of your game.

  2. In the navigation pane, choose Dev.

  3. Under Dev stage configuration, choose View in IAM console.

    The IAM console opens to the IAM role for your Dev stage.

  4. On the Permissions tab, choose Add permissions, Attach policies.

  5. Under Other permissions policies, in the search bar, enter weapon, and then press Enter.

  6. In the search results, select the ReadWeapons and WriteWeapons policies, and then choose Attach policies.

The Dev stage of your game now has permissions to read and write to your Weapons DynamoDB table.

Learn more

For more information about DynamoDB IAM policies, see Amazon DynamoDB: Allows access to a specific table in the AWS Identity and Access Management User Guide.

Create game-defined shapes

In this section, you create some game-defined shapes to include in downloaded game client code. This means that your game client works with a Weapon class instead of with JSON. This can help you find some kinds of errors at compile time instead of during runtime.

To create the WeaponType shape
  1. In the GameSparks console, choose the name of your game.

  2. In the navigation pane, choose Dev. Then, under Configuration, choose Cloud code.

  3. On the Cloud code page, choose Configure, Game-defined shapes.

  4. On the Manage game-defined shapes page, choose Create shape.

  5. On the Create shape page, under Shape definition, do the following:

    1. For Name, enter WeaponType.

    2. For Type, choose Enum.

    3. (Optional) Enter a Description.

    4. Add the following Values:

      • Blunt

      • Sharp

      • Ranged

  6. Choose Create.

To create the Weapon shape
  1. On the Manage game-defined shapes page, choose Create shape.

  2. On the Create shape page, under Shape definition, do the following:

    1. For Name, enter Weapon.

    2. For Type, choose Structure.

    3. (Optional) Enter a Description.

    4. Add the following Fields:

      Name Shape Required

      Name

      String

      Yes

      Type

      WeaponType

      Yes

      Damage

      Integer

      Yes

      Magic

      Boolean

      No

      Notes

      String

      No

      Important

      Make sure to choose No for both the Magic and Notes fields. Some of the items that you create later in this section omit these fields intentionally to demonstrate some concepts of using DynamoDB from GameSparks.

  3. Choose Create.

Summary

In this section, you created the Weapon game-defined shape, which contains the WeaponType game-defined shape. These shapes help you reduce the likelihood of bugs in your client code.

Add or replace items using DynamoDB.PutItem

To add and replace items in your DynamoDB Weapons table, create an event named AddWeapon and use the DynamoDB.PutItem cloud code function.

Create the AddWeapon event

To create the AddWeapon event
  1. In the GameSparks console, choose the name of your game.

  2. In the navigation pane, choose Dev. Then, under Configuration, choose Cloud code.

  3. On the Cloud code page, choose Create message.

  4. In the Create message dialog box, do the following:

    1. Choose Event.

    2. For Name, enter AddWeapon.

    3. (Optional) Enter a Description.

    4. Choose Create.

  5. Select Player.

  6. In the expanded Game-defined event fields pane, add the following field:

    Field name Shape Required

    Weapon

    Weapon

    Yes

  7. Choose Add event handler.

  8. In the Add event handler dialog box, do the following:

    1. For Name, enter AddWeaponHandler.

    2. (Optional) Enter a Description.

    3. Choose Save.

  9. Expand the AddWeaponHandler handler, and then add the following code:

    GameSparks().Logging().Debug("Enter AddWeaponHandler"); let newWeapon = { "Name": message.Weapon.Name, "Type": message.Weapon.Type, "Damage": message.Weapon.Damage }; if(message.Weapon.Magic !== undefined) { newWeapon.Magic = message.Weapon.Magic; } else { newWeapon.Magic = false; } if(message.Weapon.Notes !== undefined) { newWeapon.Notes = message.Weapon.Notes; }; GameSparks().Logging().Debug("Adding " + JSON.stringify(newWeapon)); const result = GameSparks().DynamoDB().PutItem("Weapons", newWeapon); GameSparks().Logging().Debug("Result: " + JSON.stringify(result)); GameSparks().Logging().Debug("Exit AddWeaponHandler");
  10. Choose Save.

Deploy your changes

You've added logic that your game can use to add an item to a DynamoDB table. Before you can test this event in your game client, deploy a new snapshot of your game configuration.

To deploy your changes
  1. In the navigation pane, under Dev, Configuration, choose Test harness.

  2. Choose Deploy as new snapshot.

  3. In the Deploy as new snapshot dialog box, do the following:

    1. (Optional) Enter a Snapshot description.

    2. Choose Save.

  4. When the You have successfully deployed… message appears, you can proceed.

Add some items to your table

Your DynamoDB Weapons table and GameSparks messages are ready for you to add and work with weapons.

To add items to the table
  1. On the Test harness page, choose the AddWeapon event.

  2. For Request body, add the following JSON:

    { "Weapon": { "Name": "Broadsword", "Type": "Sharp", "Damage": 12, "Magic": true, "Notes": "New weapon for next campaign" } }
  3. Choose Send message.

    In the Log inspector, you should see a result like the following:

    ⓘ Event sent

    Id: 5aa8f67d-2ccd-4b37-a641-48bd3c0dca5b
    Type: Custom.Game.AddWeapon
    Category: Event
    
    {"Weapon":{"Name":"Broadsword","Type":"Sharp","Damage":12,"Magic":true,"Notes":"New weapon for next campaign"}}

Add a few more items to the table

Use the AddWeapon event to add a few more weapons to Weapons. Repeat the previous procedure, replacing the Request body in the Test harness with the following JSON objects.

{ "Weapon": { "Name": "Club", "Type": "Sharp", "Damage": 4 } }
Note

Notice a few things about this example:

  • Previously, you defined the Weapon shape and made the Notes field optional, so you don't have to specify it here. Later, this topic demonstrates how you can attach and remove a note from a weapon.

  • You also defined Magic as an optional field. Even so, in the AddWeapon event, you add the Magic item to Weapons even if a value isn't specified here.

  • The weapon Type of Sharp is intentionally incorrect. Later, the topic demonstrates how to fix the Club weapon.

{ "Weapon": { "Name": "Mace", "Type": "Blunt", "Damage": 22, "Notes": "This weapon seems a bit OP" } }
{ "Weapon": { "Name": "Bow of seeking", "Type": "Ranged", "Damage": 9, "Magic": true } }
Tip

If you want to add your own weapon, choose Populate example to create a generic JSON structure. This makes it quicker to add an item.

View items in your DynamoDB table

Confirm that your new weapons appear in your DynamoDB Weapons table.

To view items in the table
  1. Open the Tables page of the DynamoDB console.

  2. On the Tables page, choose the name of your table (Weapons).

  3. Choose Explore table items.

Your new weapons appear in the Items returned card.

Summary

In this section, you:

  • Created the AddWeapon event and used the DynamoDB.PutItem cloud code function to add some items to your DynamoDB table.

  • Used the test harness to run the AddWeapon event.

  • Used the DynamoDB console to verify the items that you added to the table.

Get an item using DynamoDB.GetItem

To read an item from a table, create a request and use the DynamoDB.GetItem cloud code function.

To create the DynamoDB.GetItem request
  1. In the GameSparks console, choose the name of your game.

  2. In the navigation pane, choose Dev. Then, under Configuration, choose Cloud code.

  3. On the Cloud code page, choose Create message.

  4. In the Create message dialog box, do the following:

    1. Choose Request.

    2. For Name, enter GetWeapon.

    3. (Optional) Enter a Description.

    4. Choose Create.

  5. Select Player.

  6. In the expanded Game-defined request fields pane, add the following fields:

    Request fields

    Field name Shape Required

    Name

    String

    Yes

    Response fields

    Field name Shape Required

    Weapon

    Weapon

    Yes

  7. For Request handler, add the following code:

    GameSparks().Logging().Debug("Enter GetWeaponHandler"); const weaponItem = GameSparks().DynamoDB().GetItem("Weapons", { "Name": message.Name }); if(Object.keys(weaponItem.Item).length > 0) { GameSparks().Logging().Debug("GetItem returned: " + JSON.stringify(weaponItem)); GameSparks().Logging().Debug("Exit GetWeaponHandler"); return GameSparks().Messaging().Response({ "Weapon" : weaponItem.Item }); } else { GameSparks().Logging().Debug("GetItem returned nothing: " + JSON.stringify(weaponItem)); GameSparks().Logging().Debug("Error exit GetWeaponHandler"); return GameSparks().Messaging().Error("GameSparks.Core.ExecutionError", message.Name + " does not exist in the weapon table."); }
  8. Choose Save.

Test the request

To test the request
  1. In the navigation pane, under Dev, Configuration, choose Test harness.

  2. Choose Deploy as new snapshot.

  3. In the Deploy as new snapshot dialog box, do the following:

    1. (Optional) Enter a Snapshot description.

    2. Choose Save.

  4. When the You have successfully deployed… message appears, you can proceed.

  5. Choose the GetWeapon request.

  6. For Request body, add the following JSON:

    { "Name": "Broadsword" }
  7. Choose Send message.

    In the Log inspector, you should see results like the following:

    ✓ Response received

    Id: 277a67a4-5049-4ee5-8e2c-0ef142a1d544
    Type: Custom.Game.GetWeapon
    Category: Response
    ResponseTo: 2e64bde7-4bd6-4932-8206-809a10bc815f
    
    {"Weapon":{"Type":"Sharp","Magic":true,"Damage":12,"Notes":"New weapon for next campaign","Name":"Broadsword"}}

    ⓘ Request sent

    Id: 2e64bde7-4bd6-4932-8206-809a10bc815f
    Type: Custom.Game.GetWeapon
    Category: Request
    
    {"Name":"Broadsword"}

Summary

In this section you:

  • Created the GetWeapon cloud code request and used the DynamoDB.GetItem cloud code function to get an item from your DynamoDB Weapons table.

  • Used the test harness to run the GetWeapon request.

Modify an item using DynamoDB.UpdateItem

To modify items in a table, create an event and use the DynamoDB.UpdateItem cloud code function.

Note

As you use your cloud code messages to modify the items in Weapons, you can verify the results from the Tables page of the DynamoDB console.

Add, modify, and remove a field using the DynamoDB SET and REMOVE action values

You might want to add a field to the items in your DynamoDB Weapons table. For example, to apply notes to some weapons, but not all of them. Then, when you resolve a note, to remove it.

To try it out, create the following WeaponNotes event. The action it takes depends on the input value of the NotesAction shape:

  • AddUpdate: The DynamoDB SET action adds the item if it doesn't exist. If the item does exist, SET modifies the value of the item.

  • Remove: Uses the DynamoDB REMOVE action value to remove the item.

Create the shape

To create the NotesAction shape
  1. In the GameSparks console, choose the name of your game.

  2. In the navigation pane, choose Dev. Then, under Configuration, choose Cloud code.

  3. On the Cloud code page, choose Configure, Game-defined shapes.

  4. On the Manage game-defined shapes page, choose Create shape.

  5. On the Create shape page, under Shape definition, do the following:

    1. For Name enter NotesAction.

    2. For Type, choose Enum.

    3. Add the following Values:

      • AddUpdate

      • Remove

  6. Choose Create.

Create the event

To create the WeaponNotes event
  1. On the Cloud code page, choose Create message.

  2. In the Create message dialog box, do the following:

    1. Choose Event.

    2. For Name, enter WeaponNotes.

    3. (Optional) Enter a Description.

    4. Choose Create.

  3. Select Player.

  4. In the expanded Game-defined event fields pane, add the following fields:

    Field name Shape Required

    Name

    String

    Yes

    Action

    NotesAction

    Yes

    Notes

    String

    No

  5. Choose Add event handler.

  6. In the Add event handler dialog box, do the following:

    1. For Name, enter WeaponNotesHandler.

    2. (Optional) Enter a Description.

    3. Choose Save.

  7. Expand the WeaponNotesHandler handler, and then add the following code:

    GameSparks().Logging().Debug("Enter WeaponNotesHandler"); let result = {}; // Add or update the Notes item in Weapons if (message.Action == "AddUpdate") { let notes = ""; if(message.Notes !== undefined) { notes = message.Notes; } result = GameSparks().DynamoDB().UpdateItem("Weapons", { "Name": message.Name }, "SET Notes = :nVal", {}, { ":nVal": notes }); // Remove the Notes item from Weapons } else if (message.Action == "Remove") { result = GameSparks().DynamoDB().UpdateItem("Weapons", { "Name": message.Name }, "REMOVE Notes", {}, {}); } GameSparks().Logging().Debug("Result: " + JSON.stringify(result)); GameSparks().Logging().Debug("Exit WeaponNotesHandler");
  8. Choose Save.

Add a field to a table item

To use the WeaponNotes event to a field to a table item
  1. In the navigation pane, under Dev, Configuration, choose Test harness.

  2. Choose Deploy as new snapshot.

  3. In the Deploy as new snapshot dialog box, do the following:

    1. (Optional) Enter a Snapshot description.

    2. Choose Save.

  4. When the You have successfully deployed… message appears, you can proceed.

  5. Choose the WeaponNotes event.

  6. For Request body, add the following JSON:

    { "Name": "Bow of seeking", "Action": "AddUpdate", "Notes": "Ask Maria to review" }
  7. Choose Send message.

    In the Log inspector, you should see a result like the following:

    ⓘ Event sent

    Id: bf123799-fb0b-42a5-8003-cf972e1abc0d
    Type: Custom.Game.WeaponNotes
    Category: Event
    
    {"Name":"Bow of seeking","Action":"AddUpdate","Notes":"Ask Maria to review"}

Modify the value of a table item

As needed, you can modify the value of the field you added.

To modify the value of a table item
  1. On the Test harness page, for the WeaponNotes event, replace the Request body with the following JSON:

    { "Name": "Bow of seeking", "Action": "AddUpdate", "Notes": "Maria says it's fine" }
  2. Choose Send message.

  3. Verify your changes on the Tables page of the DynamoDB console.

Remove a field from a table item

When you no longer need the note, use the WeaponNotes event to remove it.

To remove a field from a table item
  1. On the Test harness page, for the WeaponNotes event, replace the Request body with the following JSON:

    { "Name": "Bow of seeking", "Action": "Remove" }
  2. Choose Send message.

  3. Verify your changes on the Tables page of the DynamoDB console.

Summary

In this section, you created the WeaponNotesHandler cloud code event using the following API elements:

  • The GameSparks DynamoDB.UpdateItem API operation to update items in the DynamoDB Weapons table.

  • Used the following DynamoDB API elements:

    • The DynamoDB UpdateItem operation to modify items in a table.

    • The DynamoDB UpdateExpression attribute values to add or modify (SET), or remove (REMOVE) a field from a table item.

    • DynamoDB ExpressionAttributeValues (named :nVal in this example) to set the value of a table item.

Use DynamoDB.UpdateItem parameters to modify a table item that contains a reserved keyword

Suppose you want to create an event that changes the value of the Type field. Type is a reserved keyword in DynamoDB, so you must use a substitution token to reference the item.

To modify a table item that contains a reserved keyword
  1. In the GameSparks console, choose the name of your game.

  2. In the navigation pane, choose Dev. Then, under Configuration, choose Cloud code.

  3. On the Cloud code page, choose Create message.

  4. In the Create message dialog box, do the following:

    1. Choose Event.

    2. For Name, enter UpdateWeaponType.

    3. (Optional) Enter a Description.

    4. Choose Create.

  5. Select Player.

  6. In the expanded Game-defined event fields pane, add the following fields:

    Field name Shape Required

    Name

    String

    Yes

    Type

    String

    Yes

  7. Choose Add event handler.

  8. In the Add event handler dialog box, do the following:

    1. For Name, enter UpdateWeaponTypeHandler.

    2. (Optional) Enter a Description.

    3. Choose Save.

  9. Expand the UpdateWeaponTypeHandler handler, and then add the following code:

    GameSparks().Logging().Debug("Enter UpdateWeaponTypeHandler"); const result = GameSparks().DynamoDB().UpdateItem("Weapons", { "Name": message.Name }, "SET #T = :val", { "#T":"Type" }, { ":val": message.Type }); GameSparks().Logging().Debug("Result: " + JSON.stringify(result)); GameSparks().Logging().Debug("Exit UpdateWeaponTypeHandler");
  10. Choose Save

Test the event

To test the event
  1. In the navigation pane, under Dev, Configuration, choose Test harness.

  2. Choose Deploy as new snapshot.

  3. In the Deploy as new snapshot dialog box, do the following:

    1. (Optional) Enter a Snapshot description.

    2. Choose Save.

  4. When the You have successfully deployed… message appears, you can proceed.

  5. Choose the UpdateWeaponType event.

  6. For Request body, add the following JSON:

    { "Name": "Club", "Type": "Blunt" }
  7. Choose Send message.

    In the Log inspector, you should see a result like the following:

    ⓘ Event sent

    Id: 99a14fda-63df-4e48-b2a7-084894a5a7af
    Type: Custom.Game.UpdateWeaponType
    Category: Event
    
    {"Name":"Club","Type":"Blunt"}
  8. Verify your change on the Tables page of the DynamoDB console.

Summary

In the previous section you:

  • Created the UpdateWeaponType cloud code event and used the DynamoDB.UpdateItem cloud code function to modify items in the DynamoDB Weapons table.

  • Used the following DynamoDB API elements:

    • The UpdateExpression attribute value to modify (SET) a table item.

    • The ExpressionAttributeNames to specify a substitution token (named #T in this example) so that you can refer to an item that uses a reserved DynamoDB keyword (Type in this example).

    • The ExpressionAttributeValues (named :nVal in this example) to set the value of a table item.

Learn more

For more information about GameSparks cloud code API elements that work with DynamoDB, see DynamoDB in the GameSparks Extension API Reference.