Skip to content

Commit d8fc001

Browse files
author
Adetokunbo Ige
committed
feat: code improvements
Signed-off-by: Adetokunbo Ige <[email protected]>
1 parent 9418fa6 commit d8fc001

File tree

1 file changed

+26
-21
lines changed

1 file changed

+26
-21
lines changed

todo-app/lambda_function/lambda.py

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
1-
import logging,os,uuid
1+
import logging
2+
import os
3+
import uuid
4+
from datetime import datetime
5+
from typing import List, Dict, Optional
26

37
import boto3
48
from fastapi import FastAPI, HTTPException
59
from fastapi.middleware.cors import CORSMiddleware
610
from mangum import Mangum
711
from pydantic import BaseModel
8-
from typing import List, Dict, Optional
9-
10-
from datetime import datetime
12+
from botocore.exceptions import ClientError
1113

1214
# Configure logging
1315
logging.basicConfig(level=logging.DEBUG)
@@ -18,7 +20,7 @@
1820
# Configure CORS middleware
1921
app.add_middleware(
2022
CORSMiddleware,
21-
allow_origins=["*"], # Adjust the allowed origins for your use case
23+
allow_origins=["*"],
2224
allow_credentials=True,
2325
allow_methods=["*"],
2426
allow_headers=["*"],
@@ -37,30 +39,30 @@ class TodoItem(BaseModel):
3739
@app.get("/todos", response_model=List[TodoItem])
3840
async def get_todos():
3941
try:
40-
# Perform a scan operation on the DynamoDB table
4142
response = table.scan()
42-
# Return the 'Items' from the scan result
4343
items = response.get("Items", [])
4444
logging.debug(f"Fetched {len(items)} items from DynamoDB")
4545
return items
46+
except ClientError as e:
47+
logging.error(f"DynamoDB ClientError: {e}")
48+
raise HTTPException(status_code=500, detail="Error fetching todos")
4649
except Exception as e:
4750
logging.error(f"Error getting todos: {e}")
4851
raise HTTPException(status_code=500, detail="Error fetching todos")
4952

5053
@app.post("/todos", status_code=201, response_model=TodoItem)
5154
async def create_todo(todo: TodoItem):
5255
try:
53-
# Add the current timestamp to the todo item
5456
todo_dict = todo.dict()
55-
todo_dict["timestamp"] = int(datetime.utcnow().timestamp()) # Unix timestamp in seconds
57+
todo_dict["id"] = todo_dict.get("id") or str(uuid.uuid4())
58+
todo_dict["timestamp"] = int(datetime.utcnow().timestamp())
5659

57-
# Add the todo item to DynamoDB
5860
response = table.put_item(Item=todo_dict)
5961
logging.debug(f"DynamoDB put_item response: {response}")
60-
return todo_dict # Return the updated item with the timestamp
61-
except boto3.exceptions.Boto3Error as boto_error:
62-
logging.error(f"Boto3Error: {boto_error}")
63-
raise HTTPException(status_code=500, detail=f"DynamoDB Error: {str(boto_error)}")
62+
return todo_dict
63+
except ClientError as boto_error:
64+
logging.error(f"ClientError: {boto_error}")
65+
raise HTTPException(status_code=500, detail="DynamoDB Error")
6466
except Exception as e:
6567
logging.error(f"Unexpected error creating todo: {e}")
6668
raise HTTPException(status_code=500, detail="Error creating todo")
@@ -70,9 +72,8 @@ async def update_todo(id: str, todo: Dict[str, str]):
7072
if "text" not in todo:
7173
raise HTTPException(status_code=400, detail="Missing 'text' in request body")
7274
try:
73-
# Update the todo item in DynamoDB
7475
response = table.update_item(
75-
Key={"id": id}, # Ensure id is passed as a string
76+
Key={"id": id},
7677
UpdateExpression="SET #t = :t",
7778
ExpressionAttributeNames={"#t": "text"},
7879
ExpressionAttributeValues={":t": todo["text"]},
@@ -83,20 +84,25 @@ async def update_todo(id: str, todo: Dict[str, str]):
8384
raise HTTPException(status_code=404, detail="Todo not found")
8485
logging.debug(f"Updated item: {updated_todo}")
8586
return updated_todo
87+
except ClientError as e:
88+
logging.error(f"ClientError updating todo: {e}")
89+
raise HTTPException(status_code=500, detail="Error updating todo")
8690
except Exception as e:
8791
logging.error(f"Error updating todo: {e}")
8892
raise HTTPException(status_code=500, detail="Error updating todo")
8993

9094
@app.delete("/todos/{id}", status_code=204)
9195
async def delete_todo(id: str):
9296
try:
93-
# Delete the todo item from DynamoDB
94-
response = table.delete_item(Key={"id": id}) # Ensure id is passed as a string
97+
response = table.delete_item(Key={"id": id})
9598
status_code = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
9699
if status_code != 200:
97100
raise HTTPException(status_code=404, detail="Todo not found")
98101
logging.debug(f"Deleted item with id: {id}")
99-
return {"detail": "Todo deleted successfully"}
102+
return
103+
except ClientError as e:
104+
logging.error(f"ClientError deleting todo: {e}")
105+
raise HTTPException(status_code=500, detail="Error deleting todo")
100106
except Exception as e:
101107
logging.error(f"Error deleting todo: {e}")
102108
raise HTTPException(status_code=500, detail="Error deleting todo")
@@ -105,7 +111,6 @@ async def delete_todo(id: str):
105111
async def health():
106112
try:
107113
logging.debug("Health check initiated")
108-
# Simple check to see if everything is working
109114
return {"message": "Everything looks good!"}
110115
except Exception as e:
111116
logging.error(f"Health check error: {e}")
@@ -115,4 +120,4 @@ async def health():
115120
def handler(event, context):
116121
logging.info(f"Received event: {event}")
117122
mangum_handler = Mangum(app)
118-
return mangum_handler(event, context)
123+
return mangum_handler(event, context)

0 commit comments

Comments
 (0)