Skip to content

Commit 7928ad8

Browse files
committed
Passed all tests
1 parent bcd74d4 commit 7928ad8

File tree

3 files changed

+69
-6
lines changed

3 files changed

+69
-6
lines changed

backend/api/endpoints/command.py

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,45 +2,77 @@
22
from fastapi.exceptions import HTTPException
33
from sqlmodel import Session, select
44

5+
56
from backend.api.models.request_model import CommandRequest
67
from backend.api.models.response_model import CommandListResponse, CommandSingleResponse
78
from backend.data.data_models import Command
89
from backend.data.engine import get_db
910

11+
1012
# Prefix: "/commands"
1113
command_router = APIRouter(tags=["Commands"])
1214

1315

16+
17+
1418
@command_router.get("/", response_model=CommandListResponse)
1519
def get_commands(db: Session = Depends(get_db)):
1620
"""
1721
Gets all the items
1822
23+
1924
@return Returns a list of commands
2025
"""
2126
query = select(Command)
2227
items = db.exec(query).all()
2328
return {"data": items}
2429

2530

31+
32+
2633
@command_router.post("/", response_model=CommandSingleResponse)
27-
def create_command(payload: CommandRequest):
34+
def create_command(payload: CommandRequest, db: Session = Depends(get_db)):
2835
"""
29-
Creates an item with the given payload in the database and returns this payload after pulling it from the database
36+
Creates an item with the given payload in the database and returns this payload after pulling it from the database
37+
3038
3139
@param payload: The data used to create an item
32-
@return returns a json object with field of "data" under which there is the payload now pulled from the database
40+
@return returns a json object with field of "data" under which there is the payload now pulled from the database
3341
"""
3442
# TODO:(Member) Implement this endpoint
35-
43+
new_command = Command(command_type=payload.command_type, params=payload.params)
44+
45+
db.add(new_command)
46+
db.commit()
47+
db.refresh(new_command)
48+
49+
50+
return {"data": new_command}
51+
52+
53+
3654

3755

3856
@command_router.delete("/{id}", response_model=CommandListResponse)
39-
def delete_command(id: int):
57+
def delete_command(id: int, db: Session = Depends(get_db)):
4058
"""
4159
Deletes the item with the given id if it exists. Otherwise raises a 404 error.
4260
61+
4362
@param id: The id of the item to delete
4463
@return returns the list of commands after deleting the item
4564
"""
4665
# TODO:(Member) Implement this endpoint
66+
query = select(Command)
67+
command = db.exec(query.where(Command.id == id)).first()
68+
69+
if command is None:
70+
raise HTTPException(status_code=404, detail="Item not found")
71+
72+
db.delete(command)
73+
db.commit()
74+
75+
return get_commands(db)
76+
77+
78+

backend/api/middlewares/logger_middleware.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
import time
12
from collections.abc import Callable
23
from typing import Any
34
from fastapi import Request, Response
45
from starlette.middleware.base import BaseHTTPMiddleware
56

7+
from backend.utils.logging import logger
68

79
class LoggerMiddleware(BaseHTTPMiddleware):
810
async def dispatch(
@@ -18,5 +20,14 @@ async def dispatch(
1820
@return Response from endpoint
1921
"""
2022
# TODO:(Member) Finish implementing this method
23+
start_time = time.time()
24+
request_time = time.strftime('%Y-%m-%d %H:%M:%S')
25+
logger.info(f"Request started: [{request_time}] | {request.method} | {request.url.path} | Params: {request.query_params}")
26+
2127
response = await call_next(request)
28+
29+
# Log response details and duration
30+
duration = time.time() - start_time
31+
32+
logger.info(f"Response sent: {response.status_code} | Duration: {duration:.4f}s")
2233
return response

backend/data/data_models.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,23 @@
44
from pydantic import model_validator
55
from sqlmodel import Field
66

7+
78
from backend.data.base_model import BaseSQLModel
89
from backend.data.enums import CommandStatus
910

1011

12+
13+
1114
class MainCommand(BaseSQLModel, table=True):
1215
"""
1316
Main command model.
1417
This table represents all the possible commands that can be issued.
1518
19+
1620
List of commands: https://docs.google.com/spreadsheets/d/1XWXgp3--NHZ4XlxOyBYPS-M_LOU_ai-I6TcvotKhR1s/edit?gid=564815068#gid=564815068
1721
"""
1822

23+
1924
id: int | None = Field(
2025
default=None, primary_key=True
2126
) # NOTE: Must be None for autoincrement
@@ -25,6 +30,7 @@ class MainCommand(BaseSQLModel, table=True):
2530
data_size: int
2631
total_size: int
2732

33+
2834
@model_validator(mode="after")
2935
def validate_params_format(self):
3036
"""
@@ -33,7 +39,17 @@ def validate_params_format(self):
3339
The format of the comma seperated values is "data1,data2" so no spaces between data and the commas.
3440
"""
3541
# TODO: (Member) Implement this method
36-
return self
42+
if self.params == None and self.format == None:
43+
return self
44+
elif self.params == None or self.format == None:
45+
raise ValueError()
46+
47+
if len(self.params.split(",")) == len(self.format.split(",")):
48+
return self
49+
else:
50+
raise ValueError()
51+
52+
3753

3854

3955
class Command(BaseSQLModel, table=True):
@@ -42,6 +58,7 @@ class Command(BaseSQLModel, table=True):
4258
This table holds the data related to actual commands sent from the ground station up to the OBC.
4359
"""
4460

61+
4562
id: int | None = Field(
4663
default=None, primary_key=True
4764
) # NOTE: Must be None for autoincrement
@@ -52,3 +69,6 @@ class Command(BaseSQLModel, table=True):
5269
params: str | None = None
5370
created_on: datetime = datetime.now()
5471
updated_on: datetime = datetime.now()
72+
73+
74+

0 commit comments

Comments
 (0)