Skip to content

Commit d47c41e

Browse files
author
Adetokunbo Ige
committed
feat: code improvements
Signed-off-by: Adetokunbo Ige <[email protected]>
1 parent 200fa37 commit d47c41e

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

todo-app/lambda_function/lambda.py

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -66,19 +66,16 @@ async def create_todo(todo: TodoItem):
6666
logging.error(f"Unexpected error creating todo: {e}")
6767
raise HTTPException(status_code=500, detail="Error creating todo")
6868

69-
# Define a Pydantic model for the update request body
69+
# Define the request body model for updating a todo item
7070
class UpdateTodoRequest(BaseModel):
7171
text: str
72-
completed: Optional[bool] = None # Include the `completed` field
73-
timestamp: Optional[int] = None # Make `timestamp` optional
72+
completed: bool = None # Optional field
7473

7574
# PUT endpoint to update a todo item
7675
@app.put("/todos/{id}", response_model=TodoItem)
77-
async def update_todo(id: str, request: UpdateTodoRequest):
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.")
76+
async def update_todo(id: str, request: UpdateTodoRequest, timestamp: int = None):
77+
# Use the current timestamp if one is not provided
78+
timestamp = timestamp or int(time.time())
8279

8380
if not request.text:
8481
raise HTTPException(status_code=400, detail="Missing 'text' in request body")
@@ -98,13 +95,12 @@ async def update_todo(id: str, request: UpdateTodoRequest):
9895
update_expression = "SET " + ", ".join(update_expressions)
9996

10097
try:
101-
# Use a ConditionExpression to ensure the item exists before updating
98+
# Update the item in the DynamoDB table
10299
response = table.update_item(
103-
Key={"id": id, "timestamp": timestamp},
100+
Key={"id": id, "timestamp": timestamp}, # Use `id` and `timestamp` to identify the item
104101
UpdateExpression=update_expression,
105102
ExpressionAttributeNames=expression_attribute_names,
106103
ExpressionAttributeValues=expression_attribute_values,
107-
ConditionExpression="attribute_exists(id) AND attribute_exists(timestamp)",
108104
ReturnValues="ALL_NEW"
109105
)
110106

@@ -116,29 +112,27 @@ async def update_todo(id: str, request: UpdateTodoRequest):
116112
return updated_todo
117113

118114
except ClientError as e:
119-
if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
120-
raise HTTPException(status_code=404, detail="Todo not found")
121115
logging.error(f"ClientError updating todo: {e}")
122116
raise HTTPException(status_code=500, detail="Error updating todo")
123117
except Exception as e:
124118
logging.error(f"Error updating todo: {e}")
125119
raise HTTPException(status_code=500, detail="Error updating todo")
126120

127-
# Delete a todo item in the DynamoDB table
121+
# Delete a todo item in the DynamoDB table (using only `id` as the partition key)
128122
@app.delete("/todos/{id}", status_code=204)
129-
async def delete_todo(id: str, timestamp: int):
123+
async def delete_todo(id: str):
130124
try:
131-
# Attempt to delete the item using both the partition key (id) and sort key (timestamp)
132-
response = table.delete_item(Key={"id": id, "timestamp": timestamp})
125+
# If the table uses only `id` as the partition key, we don't need a timestamp
126+
response = table.delete_item(Key={"id": id})
133127

134128
# Check if the deletion was successful by checking the response metadata
135129
if response.get("ResponseMetadata", {}).get("HTTPStatusCode") != 200:
136130
logging.warning(f"Delete operation failed for id {id}: {response}")
137131
raise HTTPException(status_code=404, detail="Todo not found")
138132

139-
logging.debug(f"Deleted item with id: {id} and timestamp: {timestamp}")
133+
logging.debug(f"Deleted item with id: {id}")
140134

141-
# No content needs to be returned for status code 204, just confirm the deletion was successful
135+
# Return nothing (status code 204)
142136
return {"detail": "Todo deleted successfully"}
143137

144138
except ClientError as e:
@@ -149,6 +143,7 @@ async def delete_todo(id: str, timestamp: int):
149143
logging.error(f"Unexpected error deleting todo with id {id}: {e}")
150144
raise HTTPException(status_code=500, detail="Error deleting todo")
151145

146+
152147
@app.get("/health")
153148
async def health():
154149
try:

0 commit comments

Comments
 (0)