Skip to content

Commit 526e030

Browse files
author
Adetokunbo Ige
committed
feat: code improvements
Signed-off-by: Adetokunbo Ige <[email protected]>
1 parent 6813966 commit 526e030

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

todo-app/lambda_function/lambda.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,10 @@ class UpdateTodoRequest(BaseModel):
7575
# PUT endpoint to update a todo item
7676
@app.put("/todos/{id}", response_model=TodoItem)
7777
async def update_todo(id: str, request: UpdateTodoRequest):
78-
# Use the current timestamp if one is not provided
79-
timestamp = request.timestamp or int(time.time())
78+
# Ensure you are using the correct timestamp
79+
timestamp = request.timestamp
80+
if not timestamp:
81+
raise HTTPException(status_code=400, detail="Missing 'timestamp' for identifying the item to update.")
8082

8183
if not request.text:
8284
raise HTTPException(status_code=400, detail="Missing 'text' in request body")
@@ -96,12 +98,13 @@ async def update_todo(id: str, request: UpdateTodoRequest):
9698
update_expression = "SET " + ", ".join(update_expressions)
9799

98100
try:
99-
# Update the item in the DynamoDB table
101+
# Use a ConditionExpression to ensure the item exists before updating
100102
response = table.update_item(
101103
Key={"id": id, "timestamp": timestamp},
102104
UpdateExpression=update_expression,
103105
ExpressionAttributeNames=expression_attribute_names,
104106
ExpressionAttributeValues=expression_attribute_values,
107+
ConditionExpression="attribute_exists(id) AND attribute_exists(timestamp)",
105108
ReturnValues="ALL_NEW"
106109
)
107110

@@ -113,6 +116,8 @@ async def update_todo(id: str, request: UpdateTodoRequest):
113116
return updated_todo
114117

115118
except ClientError as e:
119+
if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
120+
raise HTTPException(status_code=404, detail="Todo not found")
116121
logging.error(f"ClientError updating todo: {e}")
117122
raise HTTPException(status_code=500, detail="Error updating todo")
118123
except Exception as e:
@@ -121,23 +126,20 @@ async def update_todo(id: str, request: UpdateTodoRequest):
121126

122127
# Delete a todo item in the DynamoDB table
123128
@app.delete("/todos/{id}", status_code=204)
124-
async def delete_todo(id: str, timestamp: Optional[int] = None):
125-
# Use the current timestamp if one is not provided
126-
timestamp = timestamp or int(time.time())
127-
129+
async def delete_todo(id: str, timestamp: int):
128130
try:
129131
# Attempt to delete the item using both the partition key (id) and sort key (timestamp)
130132
response = table.delete_item(Key={"id": id, "timestamp": timestamp})
131133

132-
# Check if the HTTP status code indicates a successful deletion
133-
status_code = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
134-
if status_code != 200:
135-
logging.warning(f"Delete operation failed for id {id} and timestamp {timestamp}: {response}")
134+
# Check if the deletion was successful by checking the response metadata
135+
if response.get("ResponseMetadata", {}).get("HTTPStatusCode") != 200:
136+
logging.warning(f"Delete operation failed for id {id}: {response}")
136137
raise HTTPException(status_code=404, detail="Todo not found")
137138

138139
logging.debug(f"Deleted item with id: {id} and timestamp: {timestamp}")
139-
# Return nothing (status code 204)
140-
return
140+
141+
# No content needs to be returned for status code 204, just confirm the deletion was successful
142+
return {"detail": "Todo deleted successfully"}
141143

142144
except ClientError as e:
143145
logging.error(f"ClientError deleting todo with id {id}: {e}")

0 commit comments

Comments
 (0)