Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Richard H - Completed GS onboarding task #5

Closed
wants to merge 4 commits into from
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
27 changes: 22 additions & 5 deletions backend/api/endpoints/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}

45 changes: 40 additions & 5 deletions backend/api/middlewares/logger_middleware.py
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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




7 changes: 6 additions & 1 deletion backend/data/data_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading