Let's implement the ability to add todos!
Start by updating the handler in our lambda, by adding:
try {const { httpMethod, body: requestBody } = event;// if GET return todosif (httpMethod === "GET") {const response = await getAllTodos();return createResponse(response.Items || []);}if (!requestBody) {return createResponse("Missing request body", 500);}// parsing the data we sent to the serverconst data = JSON.parse(requestBody);// if POST add a todoif (httpMethod === "POST") {const todo = await addTodoItem(data);return todo? createResponse(`${todo} added to the database`): createResponse("Todo is missing", 500);}// if DELETE, delete todo (we'll imlement that in the next lesson)if (httpMethod === "DELETE") {const id = await deleteTodoItem(data);return id? createResponse(`Todo item with an id of ${id} deleted from the database`): createResponse("ID is missing", 500);}return createResponse(`We only accept GET, POST, OPTIONS and DELETE, not ${httpMethod}`,500);} catch (error) {console.log(error);return createResponse(error, 500);}
Now let's write the function for adding the todos (head here for the dynamoDB cheatsheet).
We'll be using the PUT method, which either adds an item or replaces the item if the item already exists.
const addTodoItem = async (data: { todo: string; id: string }) => {const { id, todo } = data;if (todo && todo !== "") {await dynamo.put({// params object with two properties (TableName is our env variable)TableName: tableName,Item: {id: "this_is_a_new_id",todo}}).promise();}return todo;};
👍 Let's deploy and test!
You'll need a REST client (like Insomnia or Postman) to test the POST request and of course, your app's endpoint.
For a POST request set the body to JSON (in Postman that means setting Content-Type:application/json in Headers).
Delete an item from a DynamoDB table with delete operation
Let's delete a todo!
const deleteTodoItem = async (data: { id: string }) => {const { id } = data;if (id && id !== "") {await dynamo.delete({TableName: tableName,Key: {// each todo needs a unique idid}}).promise();}return id;};
Let's test this by sending a DELETE request:
{"id": "this_is_a_new_id"}
We should get a response like this: "Todo item with an id of this_is_a_new_id deleted from the database".
👍 Validate that the todo item was indeed deleted with a new GET request.