Delete an Item from a DynamoDB table in AWS CDK with DELETE Operation

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet

The best kind of todo is the one we already completed and we can delete it from the list 🎉

In this quick lesson, we're going to learn how to delete an item from our DynamoDB table.

Instructor: [0:00] Now that we can list all of the todos and create new ones, it would be great if you could also delete a todo because there's nothing like deleting a todo item off your list. Let's implement that.

[0:10] First of all, I'm going to create a new file which I'm going to call deleteTodo.ts. As with previous Lambda functions, I'm going to paste in some boilerplate. It's very similar to what we saw in the createTodo function, with the only difference that instead of creating a new item, we need to delete an item.

[0:28] To delete an item from a DynamoDB table, I am going to need a DeleteCommand. I'm going to implement that over here. I'm going to do const command = new DeleteCommand, and I need to pass in two things. I need to pass in the TableName, but I also need to pass in the Key.

[0:46] The Key is the primary key of the item that I want to delete. TableName is going to be the tableName passed in through the environment variables, and the Key is going to be the id provided to us by the client, which we can see over here. Of course, we need to invoke the command, so I'm going to do await docClient.send(command).

[1:07] With all of that in place, let me go back to our todo-backend construct. The delete function is very similar to the createTodosFunction. So similar that, in fact, I'm going to copy all of that and paste that over here, and I'm going to replace create with delete.

[1:24] Notice that I need to grantReadWriteData to deleteTodosFunction, because otherwise, I will not be able to delete an item from a DynamoDB table. To make sure that everything is OK, I'm going to go ahead and deploy this stack. Let me open up the terminal and run cdk deploy.

[1:40] Before we deploy, we are asked whether we would like deleteTodos to be able to delete an item from our TodoDatabase. This is exactly what we want, so I'm going to hit y, and hit Enter. After a successful deployment, we have all the three of our Lambda functions ready to go. Right now we can list all the todos, create a todo, and delete a todo from the list.