Skip to content

Commit 57208fd

Browse files
author
Adetokunbo Ige
committed
feat: code improvements
Signed-off-by: Adetokunbo Ige <[email protected]>
1 parent b06c28b commit 57208fd

File tree

2 files changed

+21
-30
lines changed

2 files changed

+21
-30
lines changed

todo-app/__main__.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,23 +14,18 @@
1414

1515
aws.config.region = region
1616

17-
# First, create the DynamoDB table
17+
# First, create the DynamoDB table with just `id` as the primary key
1818
dynamodb_table = aws.dynamodb.Table(
1919
f"todo-{environment}",
2020
name=f"todo-{environment}",
21-
hash_key="id",
22-
range_key="timestamp",
21+
hash_key="id", # Only `id` as the partition key
2322
attributes=[
2423
aws.dynamodb.TableAttributeArgs(
2524
name="id",
26-
type="S"
27-
),
28-
aws.dynamodb.TableAttributeArgs(
29-
name="timestamp",
30-
type="N"
25+
type="S" # `S` for string type (use appropriate type for `id`)
3126
),
3227
],
33-
billing_mode="PAY_PER_REQUEST",
28+
billing_mode="PAY_PER_REQUEST", # On-demand billing mode
3429
tags={
3530
"Environment": environment,
3631
"Created_By": "Pulumi"

todo-app/lambda_function/lambda.py

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,7 @@ class UpdateTodoRequest(BaseModel):
7373

7474
# PATCH endpoint to update a todo item
7575
@app.patch("/todos/{id}", response_model=TodoItem)
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())
79-
76+
async def update_todo(id: str, request: UpdateTodoRequest):
8077
# Initialize the list of update expressions and expression attributes
8178
update_expressions = []
8279
expression_attribute_names = {}
@@ -100,19 +97,21 @@ async def update_todo(id: str, request: UpdateTodoRequest, timestamp: int = None
10097
update_expression = "SET " + ", ".join(update_expressions)
10198

10299
try:
100+
# First, check if the item exists
101+
response = table.get_item(Key={"id": id})
102+
if "Item" not in response:
103+
raise HTTPException(status_code=404, detail="Todo not found")
104+
103105
# Update the item in the DynamoDB table
104106
response = table.update_item(
105-
Key={"id": id, "timestamp": timestamp}, # Use `id` and `timestamp` to identify the item
107+
Key={"id": id}, # Only using `id` as the partition key
106108
UpdateExpression=update_expression,
107109
ExpressionAttributeNames=expression_attribute_names,
108110
ExpressionAttributeValues=expression_attribute_values,
109111
ReturnValues="ALL_NEW"
110112
)
111113

112114
updated_todo = response.get("Attributes")
113-
if not updated_todo:
114-
raise HTTPException(status_code=404, detail="Todo not found")
115-
116115
logging.debug(f"Updated item: {updated_todo}")
117116
return updated_todo
118117

@@ -126,32 +125,29 @@ async def update_todo(id: str, request: UpdateTodoRequest, timestamp: int = None
126125

127126
# Delete a todo item in the DynamoDB table (using only `id` as the partition key)
128127
@app.delete("/todos/{id}", status_code=204)
129-
async def delete_todo(id: str, timestamp: int = None):
128+
async def delete_todo(id: str):
130129
try:
131-
# If timestamp is not provided, use the current timestamp
132-
timestamp = timestamp or int(time.time())
130+
# Attempt to delete the item using the partition key (id)
131+
response = table.delete_item(Key={"id": id})
133132

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})
136-
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}")
133+
# If no item was deleted (i.e., no such key exists), return a 404 error
134+
if not response.get("Attributes"):
140135
raise HTTPException(status_code=404, detail="Todo not found")
141136

142-
logging.debug(f"Deleted item with id: {id} and timestamp: {timestamp}")
143-
# Return nothing (status code 204)
137+
logging.debug(f"Deleted item with id: {id}")
138+
# Return nothing (status code 204) to indicate successful deletion
144139
return {"detail": "Todo deleted successfully"}
145140

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

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

154149

150+
155151
@app.get("/health")
156152
async def health():
157153
try:

0 commit comments

Comments
 (0)