diff --git a/backend/api/endpoints/command.py b/backend/api/endpoints/command.py index 583ea5a..d9c53d6 100644 --- a/backend/api/endpoints/command.py +++ b/backend/api/endpoints/command.py @@ -24,23 +24,40 @@ 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 @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 - + + new_command = Command(**payload.model_dump()); + + db.add(new_command) + db.commit() + db.refresh(new_command) + + return {"data" : new_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_to_delete = db.get(Command, id) + if not command_to_delete: + raise HTTPException(status_code=404) + + db.delete(command_to_delete) + db.commit() + + remaining_commands = db.exec(select(Command)).all() + + return {"data": remaining_commands} + diff --git a/backend/api/middlewares/logger_middleware.py b/backend/api/middlewares/logger_middleware.py index 44daa5d..a3a2252 100644 --- a/backend/api/middlewares/logger_middleware.py +++ b/backend/api/middlewares/logger_middleware.py @@ -1,13 +1,13 @@ from collections.abc import Callable +from time import time from typing import Any from fastapi import Request, Response from starlette.middleware.base import BaseHTTPMiddleware +from backend.utils.logging import logger class LoggerMiddleware(BaseHTTPMiddleware): - async def dispatch( - self, request: Request, call_next: Callable[[Request], Any] - ) -> Response: + async def dispatch(self, request: Request, call_next: Callable[[Request], Any]) -> Response: """ Logs all incoming and outgoing request, response pairs. This method logs the request params, datetime of request, duration of execution. Logs should be printed using the custom logging module provided. @@ -17,6 +17,41 @@ async def dispatch( @param call_next: Endpoint or next middleware to be called (if any, this is the next middleware in the chain of middlewares, it is supplied by FastAPI) @return Response from endpoint """ - # TODO:(Member) Finish implementing this method - response = await call_next(request) + + start_time = time() + + logger.info(f"Incoming request: {request.method} {request.url.path}"); + logger.info(f"Params: {request.query_params}"); + logger.info(f"Headers: {dict(request.headers)}"); + + try: + req_body = await request.body() + logger.info(f"Request body: {req_body}") + except Exception as e: + logger.warning(f"Error reading body!. Error: {str(e)}") + + + try: + response = await call_next(request) + logger.info(f"Outgoing response: {request.method} {request.url.path}") + logger.info(f"Response status: {response.status_code}") + logger.info(f"Response headers: {dict(response.headers)}") + + try: + res_body = await response.body() + logger.info(f"Response body: {res_body}") + except Exception as e: + logger.warning(f"Error reading body!. Error: {str(e)}") + + except Exception as e: + logger.warning(f"Error calling next middleware!. Error: {str(e)}") + + + end_time = time() - start_time + logger.info(f"Response time: {end_time}") + return response + + + + diff --git a/backend/data/data_models.py b/backend/data/data_models.py index 68adddb..b8adebe 100644 --- a/backend/data/data_models.py +++ b/backend/data/data_models.py @@ -33,7 +33,12 @@ 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 + if not self.params and not self.format: + return self + elif self.params and self.format and self.params.count(",") == self.format.count(","): + return self + else: + raise ValueError("Validation failed! 'params' and 'format' must either both be None or contain the same number of comma-separated values.") class Command(BaseSQLModel, table=True):