Skip to content

Commit 6405bbb

Browse files
author
Adetokunbo Ige
committed
feat: code improvements
Signed-off-by: Adetokunbo Ige <[email protected]>
1 parent bb1ae64 commit 6405bbb

File tree

1 file changed

+27
-19
lines changed

1 file changed

+27
-19
lines changed

todo-app/lambda_function/lambda.py

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -71,26 +71,31 @@ class UpdateTodoRequest(BaseModel):
7171
text: str
7272
completed: bool = None # Optional field
7373

74-
# PUT endpoint to update a todo item
75-
@app.put("/todos/{id}", response_model=TodoItem)
74+
# PATCH endpoint to update a todo item
75+
@app.patch("/todos/{id}", response_model=TodoItem)
7676
async def update_todo(id: str, request: UpdateTodoRequest, timestamp: int = None):
7777
# Use the current timestamp if one is not provided
7878
timestamp = timestamp or int(time.time())
7979

80-
if not request.text:
81-
raise HTTPException(status_code=400, detail="Missing 'text' in request body")
80+
# Initialize the list of update expressions and expression attributes
81+
update_expressions = []
82+
expression_attribute_names = {}
83+
expression_attribute_values = {}
8284

83-
# Prepare the update expressions
84-
update_expressions = ["#t = :t"]
85-
expression_attribute_names = {"#t": "text"}
86-
expression_attribute_values = {":t": request.text}
85+
# Only include fields that are present in the request
86+
if request.text:
87+
update_expressions.append("#t = :t")
88+
expression_attribute_names["#t"] = "text"
89+
expression_attribute_values[":t"] = request.text
8790

88-
# Add the `completed` field to the update if it's provided
8991
if request.completed is not None:
9092
update_expressions.append("#c = :c")
9193
expression_attribute_names["#c"] = "completed"
9294
expression_attribute_values[":c"] = request.completed
9395

96+
if not update_expressions:
97+
raise HTTPException(status_code=400, detail="No fields provided to update")
98+
9499
# Construct the UpdateExpression string
95100
update_expression = "SET " + ", ".join(update_expressions)
96101

@@ -118,29 +123,32 @@ async def update_todo(id: str, request: UpdateTodoRequest, timestamp: int = None
118123
logging.error(f"Error updating todo: {e}")
119124
raise HTTPException(status_code=500, detail="Error updating todo")
120125

126+
121127
# Delete a todo item in the DynamoDB table (using only `id` as the partition key)
122128
@app.delete("/todos/{id}", status_code=204)
123-
async def delete_todo(id: str):
129+
async def delete_todo(id: str, timestamp: int = None):
124130
try:
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})
131+
# If timestamp is not provided, use the current timestamp
132+
timestamp = timestamp or int(time.time())
133+
134+
# Attempt to delete the item using both the partition key (id) and sort key (timestamp)
135+
response = table.delete_item(Key={"id": id, "timestamp": timestamp})
127136

128-
# Check if the deletion was successful by checking the response metadata
129-
if response.get("ResponseMetadata", {}).get("HTTPStatusCode") != 200:
130-
logging.warning(f"Delete operation failed for id {id}: {response}")
137+
# Check if the HTTP status code indicates a successful deletion
138+
if "ResponseMetadata" not in response or response["ResponseMetadata"].get("HTTPStatusCode") != 200:
139+
logging.warning(f"Delete operation failed for id {id} and timestamp {timestamp}: {response}")
131140
raise HTTPException(status_code=404, detail="Todo not found")
132141

133-
logging.debug(f"Deleted item with id: {id}")
134-
142+
logging.debug(f"Deleted item with id: {id} and timestamp: {timestamp}")
135143
# Return nothing (status code 204)
136144
return {"detail": "Todo deleted successfully"}
137145

138146
except ClientError as e:
139-
logging.error(f"ClientError deleting todo with id {id}: {e}")
147+
logging.error(f"ClientError deleting todo with id {id} and timestamp {timestamp}: {e}")
140148
raise HTTPException(status_code=500, detail=f"Error deleting todo: {str(e)}")
141149

142150
except Exception as e:
143-
logging.error(f"Unexpected error deleting todo with id {id}: {e}")
151+
logging.error(f"Unexpected error deleting todo with id {id} and timestamp {timestamp}: {e}")
144152
raise HTTPException(status_code=500, detail="Error deleting todo")
145153

146154

0 commit comments

Comments
 (0)