Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions backend/api/endpoints/command.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from fastapi import HTTPException
from fastapi import APIRouter, Depends
from sqlmodel import Session, select

Expand All @@ -23,23 +24,35 @@ def get_commands(db: Session = Depends(get_db)):


@command_router.post("/", response_model=CommandSingleResponse)
def create_command(payload: CommandRequest):
def create_command(payload: CommandRequest, db: Session = Depends(get_db)):
"""
Creates an item with the given payload in the database and returns this payload after pulling it from the database
Creates an item with the given payload in the database and returns this
payload after pulling it from the database

:param payload: The data used to create an item
:return: returns a json object with field of "data" under which there is the payload now pulled from the database
"""
# TODO:(Member) Implement this endpoint


# TODO:(Member) Implement this endpoint'
payload = payload.model_dump()
command = Command(**payload)
db.add(command)
db.commit()
db.refresh(command)
return {"data": command}

@command_router.delete("/{id}", response_model=CommandListResponse)
def delete_command(id: int):
def delete_command(id: int, db: Session = Depends(get_db)):
"""
Deletes the item with the given id if it exists. Otherwise raises a 404 error.

:param id: The id of the item to delete
:return: returns the list of commands after deleting the item
"""
# TODO:(Member) Implement this endpoint
command = db.get(entity=Command, ident=id)
if command:
db.delete(command)
db.commit()
return get_commands(db)
else:
raise HTTPException(status_code=404)
48 changes: 46 additions & 2 deletions backend/api/middlewares/logger_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
from typing import Any
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from datetime import datetime

from backend.utils.logging import logger

class LoggerMiddleware(BaseHTTPMiddleware):
async def dispatch(
Expand All @@ -18,5 +20,47 @@ async def dispatch(
:return: Response from endpoint
"""
# TODO:(Member) Finish implementing this method
response = await call_next(request)
return response
time_start = datetime.now()
request_body = None
params = None

try:
if request.method != "GET":
request_body = await request.json()
except Exception as e:
logger.info(f"Exception: {e}")

if request_body:
params = request_body["params"]

logger.info(f"Request URL: {request.url}")
logger.info(f"Request method: {request.method}")
logger.info(f"Request params: {params}")
logger.info(f"Time of call: {time_start}")

try:
response = await call_next(request)
except Exception as e:
response = Response("Internal Server Error", status_code=500)
logger.info(f"Exception {e}")
return response

time_end = datetime.now()
time_diff = time_end - time_start
time_diff_ms = time_diff.total_seconds() * 1000
response_header = response.headers
response_body = {"data": None}

try:
response_body_bytes = [chunk async for chunk in response.body_iterator]
response_body = b''.join(response_body_bytes).decode("utf-8")
except Exception as e:
logger.info(f"Exception {e}")

logger.info(f"Response Status: {response.status_code}")
logger.info(f"Response Body: {response_body}")
logger.info(f"Response header: {response_header}")
logger.info(f"Length of call (ms): {time_diff_ms}")

return Response(content=response_body, status_code=response.status_code,
headers=dict(response.headers), media_type=response.media_type)
8 changes: 7 additions & 1 deletion backend/data/data_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@ def validate_params_format(self):
The format of the comma seperated values is "data1,data2" so no spaces between data and the commas.
"""
# TODO: (Member) Implement this method
return self
# Done!
if self.params is None and self.format is None:
return self
elif self.params and self.format and len(list(self.params.split(","))) == len(list(self.params.split(","))):
return self
else:
raise ValueError("Params is None") if self.params is None else ValueError("Format is None")


class Command(BaseSQLModel, table=True):
Expand Down