Skip to content

Commit a400ea2

Browse files
committed
Backend Onboarding
1 parent 12596fb commit a400ea2

File tree

3 files changed

+50
-3
lines changed

3 files changed

+50
-3
lines changed

backend/api/endpoints/command.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,23 +24,35 @@ def get_commands(db: Session = Depends(get_db)):
2424

2525

2626
@command_router.post("/", response_model=CommandSingleResponse)
27-
def create_command(payload: CommandRequest):
27+
def create_command(payload: CommandRequest, db: Session = Depends(get_db)):
2828
"""
2929
Creates an item with the given payload in the database and returns this payload after pulling it from the database
3030
3131
@param payload: The data used to create an item
3232
@return returns a json object with field of "data" under which there is the payload now pulled from the database
3333
"""
3434
# TODO:(Member) Implement this endpoint
35+
command = Command(**payload.model_dump())
36+
db.add(command)
37+
db.commit()
38+
db.refresh(command)
39+
return {"data": command}
3540

3641

3742

3843
@command_router.delete("/{id}", response_model=CommandListResponse)
39-
def delete_command(id: int):
44+
def delete_command(id: int, db: Session = Depends(get_db)):
4045
"""
4146
Deletes the item with the given id if it exists. Otherwise raises a 404 error.
4247
4348
@param id: The id of the item to delete
4449
@return returns the list of commands after deleting the item
4550
"""
4651
# TODO:(Member) Implement this endpoint
52+
command = db.get(Command, id)
53+
if not command:
54+
raise HTTPException(status_code=404, detail="Command not found")
55+
db.delete(command)
56+
db.commit()
57+
items = db.exec(select(Command)).all()
58+
return {"data": items}

backend/api/middlewares/logger_middleware.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1+
import time
2+
from datetime import datetime
13
from collections.abc import Callable
24
from typing import Any
35
from fastapi import Request, Response
46
from starlette.middleware.base import BaseHTTPMiddleware
57

8+
import logging
9+
custom_logger = logging.getLogger("my_logger")
610

711
class LoggerMiddleware(BaseHTTPMiddleware):
812
async def dispatch(
@@ -18,5 +22,22 @@ async def dispatch(
1822
@return Response from endpoint
1923
"""
2024
# TODO:(Member) Finish implementing this method
25+
start_time = time.time()
26+
timestamp = datetime.utcnow().isoformat()
27+
28+
# Log incoming request
29+
custom_logger.info(f"[{timestamp}] Incoming request: {request.method} {request.url}")
30+
custom_logger.info(f"Headers: {dict(request.headers)}")
31+
if request.query_params:
32+
custom_logger.info(f"Query Params: {dict(request.query_params)}")
33+
34+
# Process request
2135
response = await call_next(request)
36+
37+
# Measure execution time
38+
duration = time.time() - start_time
39+
custom_logger.info(
40+
f"Response status: {response.status_code} | Duration: {duration:.4f} seconds"
41+
)
42+
2243
return response

backend/data/data_models.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,21 @@ def validate_params_format(self):
3333
The format of the comma seperated values is "data1,data2" so no spaces between data and the commas.
3434
"""
3535
# TODO: (Member) Implement this method
36-
return self
36+
if self.params is None and self.format is None:
37+
return self # Valid case: both are None
38+
39+
if self.params is not None and self.format is not None:
40+
params_count = len(self.params.split(","))
41+
format_count = len(self.format.split(","))
42+
if params_count == format_count:
43+
return self
44+
else:
45+
raise ValueError(
46+
f"Mismatch between number of params ({params_count}) and format items ({format_count})."
47+
)
48+
49+
50+
raise ValueError("Both 'params' and 'format' must be None or must have the same number of comma-separated values.")
3751

3852

3953
class Command(BaseSQLModel, table=True):

0 commit comments

Comments
 (0)