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.
Topics
- Deploy your game for the first time
- Create a DynamoDB table
- Give your game permission to access your table
- Create game-defined shapes
- Add or replace items using DynamoDB.PutItem
- Get an item using DynamoDB.GetItem
- Modify an item using DynamoDB.UpdateItem
- Use DynamoDB.UpdateItem parameters to modify a table item that contains a reserved keyword
- Learn more
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
-
In the GameSparks console
, choose the name of your game. -
In the navigation pane, choose Dev.
-
On the Dev page, under Snapshot, choose Deploy as new snapshot.
-
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
-
In the GameSparks console
, choose the name of your game. -
Make note of the current AWS Region selected in the upper-right corner of the console.
-
Open the Tables page
of the DynamoDB console. -
Make sure that the Region in the upper-right corner of the DynamoDB console matches the Region of your game.
-
Choose Create table.
-
On the Create table page, under Table details, do the following:
-
For Table name, enter
Weapons
. -
For Partition key, enter
Name
.
-
-
Choose Create table.
On the Tables page, wait for the Status of your new table to become Active.
-
Choose the name of your table (
Weapons
). -
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
-
Open the IAM Create policy page
. -
Choose the JSON tab.
-
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. -
Choose Next: Tags, and then choose Next: Review.
-
On the Review policy page, do the following:
-
For Name, enter
ReadWeapons
. -
(Optional) Enter a Description.
-
Choose Create policy.
-
-
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. -
Choose Next: Tags, and then choose Next: Review.
-
On the Review policy page, do the following:
-
For Name, enter
WriteWeapons
. -
(Optional) Enter a Description.
-
Choose Create policy.
-
To attach your IAM policies
-
In the GameSparks console
, choose the name of your game. -
In the navigation pane, choose Dev.
-
Under Dev stage configuration, choose View in IAM console.
The IAM console opens to the IAM role for your Dev stage.
-
On the Permissions tab, choose Add permissions, Attach policies.
-
Under Other permissions policies, in the search bar, enter
weapon
, and then press Enter. -
In the search results, select the
ReadWeapons
andWriteWeapons
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
-
In the GameSparks console
, choose the name of your game. -
In the navigation pane, choose Dev. Then, under Configuration, choose Cloud code.
-
On the Cloud code page, choose Configure, Game-defined shapes.
-
On the Manage game-defined shapes page, choose Create shape.
-
On the Create shape page, under Shape definition, do the following:
-
For Name, enter
WeaponType
. -
For Type, choose Enum.
-
(Optional) Enter a Description.
-
Add the following Values:
-
Blunt
-
Sharp
-
Ranged
-
-
-
Choose Create.
To create the Weapon
shape
-
On the Manage game-defined shapes page, choose Create shape.
-
On the Create shape page, under Shape definition, do the following:
-
For Name, enter
Weapon
. -
For Type, choose Structure.
-
(Optional) Enter a Description.
-
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 theMagic
andNotes
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.
-
-
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
-
In the GameSparks console
, choose the name of your game. -
In the navigation pane, choose Dev. Then, under Configuration, choose Cloud code.
-
On the Cloud code page, choose Create message.
-
In the Create message dialog box, do the following:
-
Choose Event.
-
For Name, enter
AddWeapon
. -
(Optional) Enter a Description.
-
Choose Create.
-
-
Select Player.
-
In the expanded Game-defined event fields pane, add the following field:
Field name Shape Required Weapon
Weapon
Yes
-
Choose Add event handler.
-
In the Add event handler dialog box, do the following:
-
For Name, enter
AddWeaponHandler
. -
(Optional) Enter a Description.
-
Choose Save.
-
-
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");
-
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
-
In the navigation pane, under Dev, Configuration, choose Test harness.
-
Choose Deploy as new snapshot.
-
In the Deploy as new snapshot dialog box, do the following:
-
(Optional) Enter a Snapshot description.
-
Choose Save.
-
-
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
-
On the Test harness page, choose the
AddWeapon
event. -
For Request body, add the following JSON:
{ "Weapon": { "Name": "Broadsword", "Type": "Sharp", "Damage": 12, "Magic": true, "Notes": "New weapon for next campaign" } }
-
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 theMagic
item toWeapons
even if a value isn't specified here. -
The weapon
Type
ofSharp
is intentionally incorrect. Later, the topic demonstrates how to fix theClub
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
-
Open the Tables page
of the DynamoDB console. -
On the Tables page, choose the name of your table (
Weapons
). -
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
-
In the GameSparks console
, choose the name of your game. -
In the navigation pane, choose Dev. Then, under Configuration, choose Cloud code.
-
On the Cloud code page, choose Create message.
-
In the Create message dialog box, do the following:
-
Choose Request.
-
For Name, enter
GetWeapon
. -
(Optional) Enter a Description.
-
Choose Create.
-
-
Select Player.
-
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
-
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."); }
-
Choose Save.
Test the request
To test the request
-
In the navigation pane, under Dev, Configuration, choose Test harness.
-
Choose Deploy as new snapshot.
-
In the Deploy as new snapshot dialog box, do the following:
-
(Optional) Enter a Snapshot description.
-
Choose Save.
-
-
When the You have successfully deployed… message appears, you can proceed.
-
Choose the
GetWeapon
request. -
For Request body, add the following JSON:
{ "Name": "Broadsword" }
-
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 DynamoDBWeapons
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
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 DynamoDBSET
action adds the item if it doesn't exist. If the item does exist,SET
modifies the value of the item. -
Remove
: Uses the DynamoDBREMOVE
action value to remove the item.
Create the shape
To create the NotesAction
shape
-
In the GameSparks console
, choose the name of your game. -
In the navigation pane, choose Dev. Then, under Configuration, choose Cloud code.
-
On the Cloud code page, choose Configure, Game-defined shapes.
-
On the Manage game-defined shapes page, choose Create shape.
-
On the Create shape page, under Shape definition, do the following:
-
For Name enter
NotesAction
. -
For Type, choose Enum.
-
Add the following Values:
-
AddUpdate
-
Remove
-
-
-
Choose Create.
Create the event
To create the WeaponNotes
event
-
On the Cloud code page, choose Create message.
-
In the Create message dialog box, do the following:
-
Choose Event.
-
For Name, enter
WeaponNotes
. -
(Optional) Enter a Description.
-
Choose Create.
-
-
Select Player.
-
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
-
Choose Add event handler.
-
In the Add event handler dialog box, do the following:
-
For Name, enter
WeaponNotesHandler
. -
(Optional) Enter a Description.
-
Choose Save.
-
-
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");
-
Choose Save.
Add a field to a table item
To use the WeaponNotes
event to a field to a table item
-
In the navigation pane, under Dev, Configuration, choose Test harness.
-
Choose Deploy as new snapshot.
-
In the Deploy as new snapshot dialog box, do the following:
-
(Optional) Enter a Snapshot description.
-
Choose Save.
-
-
When the You have successfully deployed… message appears, you can proceed.
-
Choose the
WeaponNotes
event. -
For Request body, add the following JSON:
{ "Name": "Bow of seeking", "Action": "AddUpdate", "Notes": "Ask Maria to review" }
-
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
-
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" }
-
Choose Send message.
-
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
-
On the Test harness page, for the
WeaponNotes
event, replace the Request body with the following JSON:{ "Name": "Bow of seeking", "Action": "Remove" }
-
Choose Send message.
-
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
-
In the GameSparks console
, choose the name of your game. -
In the navigation pane, choose Dev. Then, under Configuration, choose Cloud code.
-
On the Cloud code page, choose Create message.
-
In the Create message dialog box, do the following:
-
Choose Event.
-
For Name, enter
UpdateWeaponType
. -
(Optional) Enter a Description.
-
Choose Create.
-
-
Select Player.
-
In the expanded Game-defined event fields pane, add the following fields:
Field name Shape Required Name
String
Yes
Type
String
Yes
-
Choose Add event handler.
-
In the Add event handler dialog box, do the following:
-
For Name, enter
UpdateWeaponTypeHandler
. -
(Optional) Enter a Description.
-
Choose Save.
-
-
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");
-
Choose Save
Test the event
To test the event
-
In the navigation pane, under Dev, Configuration, choose Test harness.
-
Choose Deploy as new snapshot.
-
In the Deploy as new snapshot dialog box, do the following:
-
(Optional) Enter a Snapshot description.
-
Choose Save.
-
-
When the You have successfully deployed… message appears, you can proceed.
-
Choose the
UpdateWeaponType
event. -
For Request body, add the following JSON:
{ "Name": "Club", "Type": "Blunt" }
-
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"}
-
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 DynamoDBWeapons
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.