For an 'id' in my DynamoDB table (e.g. e5eb02ae-04d5-4331-91e6-11efaaf12ea5
), i want to create a column called Pairs. In that one Pairs columns i would have
['a', 'b'],
['c', 'd'],
['e', 'f'],
etc....
The also need to update Pairs if a new pair arrives, say ['g', 'h']. Right now, my update() below, replaces the pair every time.
const newPairs = {
number1: "g",
number2: "h"
}
const updateinfo = {
id: "e5eb02ae-04d5-4331-91e6-11efaaf12ea5",
Pairs: newPairs
}
try {
await API.graphql(graphqlOperation (UpdateInfo, { input: updateinfo })) //mutation
console.log('success')
}
catch (err) {
console.log(err)
}
How do i do this, ensuring that my list is just appended to with the new pair, not replaced entirely with [g, h]?
If you can post your schema / resolver mapping template I can offer more specific advice, but I'll do my best to answer this with what you've posted so far.
Simple Way
If you have the existing item already, one way to do this would be to update the existing Pairs and pass that to your existing mutation.
Using DynamoDB functions
If you do not have the existing item or if
Pairs
can be pretty big, AWS DynamoDB'slist_append
function can be used instead.Here is an example with a specific mutation that uses it.
This way is also nice because if someone else updates Pairs, you won't overwrite their update. You can also add the new Pair to the beginning of the list by inverting the order of your arguments to the
list_append
function.DynamoDB Functions with AWS Amplify
If your project was generated by AWS Amplify, you will need to add a customer resolver.
Step 1: Add a new mutation to your schema
Step 2: Add a resolver request mapping template
Step 3: Add a resolver response mapping template
Step 4: Add your custom resolver to your CustomResources stack
Step 5: Build and Deploy your new changes
amplify api gql-compile
to see the new changes in your generated code (optional).amplify push
to deploy your changes.Now you can either run
amplify api console
or use the new generated code to test the changes with your new mutation.To generate the new code you can run
amplify codegen
. You should then be able to do something like thisAdditional Examples
Remember to update your CustomResources.json file with any new resolvers you add.
Adding a single item to a list of scalar values
Adding multiple items to a list of scalar values
Note: I am introducing
$util.dynamodb.toDynamoDBJson
here to make constructing our VTL easier. I've been explicit thus far but this utility can simplify a lot of the work. More hereRemove an item from a list of scalar values
Removing elements from lists in DynamoDB is done using the REMOVE action. You must specify a non-negative index as part of the update expression. If the index does not exist on the item, your request will not fail (e.g. no index out of bounds exceptions).