Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use transactions to check if an item exists in one table before updating a second table using AWS.DynamoDB.DocumentClient?

I am new to DynamoDB. I have a DynamoDB table called 'kids-profiles' that lists child profiles for a user (primary partition key 'userId', primary sort key 'childId'). I have a second table called 'kids-tasks' that lists tasks for a child (primary partition key 'childId', primary sort key 'taskId'). I would like to atomically add an item to the 'kids-tasks' table only if the 'childId' exists in the 'kids-profiles' table.

I am trying to use the transactWrite method of the AWS.DynamoDB.DocumentClient class (https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html) to achieve this, but I can't get it to work. First, when I try to add a ConditionCheck to the TransactionItems, it says "TransactItems can only contain one of Check, Put, Update or Delete". So I have changed "ConditionCheck" to "Check" instead, assuming that is correct even though it is not mentioned in the documentation. Second, when I do get it to execute, it adds the task to the 'kids-tasks' table regardless of whether or not the 'childId' exists in the 'kids-profiles' table.

    const params = {
        TransactItems: [ 
            {
                Check: {
                    TableName: "kids-profiles",
                    Key: {
                        userId:   userId,
                        childId:  childId,
                    },
                    ConditionExpression: "attribute_exists(childId)",
                },
                Put: {
                    TableName: "kids-tasks",
                    Item: {
                        childId:  childId,
                        taskId:   uuid.v1(),
                        title:    title,
                    }
                }
            }
        ]
    };

    try 
    {
        await dynamoDb.transactWrite(params).promise();
        console.log("Success!");
    } 
    catch (error) 
    {
        console.log("Error");
    }
like image 407
Susan Avatar asked Sep 20 '25 21:09

Susan


1 Answers

Divide objects into individual Operations.

 const params = {
     TransactItems: [ 
         {
            ConditionCheck: {
                ...
            },
+        }, // <------ !!!!!
+        {
             Put: {
                ...
         }
     ]
 };
like image 106
Legokichi Duckscallion Avatar answered Sep 22 '25 11:09

Legokichi Duckscallion