Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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: 23 additions & 4 deletions backend/api/endpoints/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,42 @@ 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

command = Command(**payload.model_dump())
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

query = select(Command).where(Command.id == id)
result = db.exec(query).first()

if not result:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use is None here

raise HTTPException(status_code=404, detail=f"Command with id {id} not found.")

db.delete(result)
db.commit()

query = select(Command)
items = db.exec(query).all()
return {"data": items}
8 changes: 7 additions & 1 deletion backend/api/middlewares/logger_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from typing import Any
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from loguru import logger
from time import perf_counter


class LoggerMiddleware(BaseHTTPMiddleware):
Expand All @@ -17,6 +19,10 @@ 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
start = perf_counter()

response = await call_next(request)

duration = perf_counter() - start
logger.info
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good you are using perf_counter but the logging portion isnt done yet

return response
15 changes: 14 additions & 1 deletion backend/data/data_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,20 @@ def validate_params_format(self):
In either of these cases return self. Otherwise raise a ValueError.
The format of the comma seperated values is "data1,data2" so no spaces between data and the commas.
"""
# TODO: (Member) Implement this method
validated_params = self.params
validated_format = self.format
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kinda of redundant ngl, the right side is shorter and more explicit


if validated_params == None and validated_format == None:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use is instead of == when doing comparison against None

return self
elif isinstance(validated_params, str) and (isinstance(validated_format, str)) and validated_params.count(",") == validated_format.count(","):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good you are checking if they are strings here. But .count() doesnt produce the correct result. For example "a,b" and "a," have the same number of commas but not the same number of comma separated values (empty isnt considered valid here)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the redundant () around the 2nd isinstance

return self
else:
raise(ValueError
(f"""params and format must both be either None or have the same number of comma seperated values,
recieved:
params: {validated_params}
format: {validated_format}\n"""))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove the else and unindent the raise. Also remove the () after the raise


return self
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This return will never be reached because of the else raise block above



Expand Down
3 changes: 1 addition & 2 deletions frontend/src/data/request.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export interface CommandRequest {
name: string
command_type: string
params: string | null
format: string | null
}

10 changes: 10 additions & 0 deletions frontend/src/display/command_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,13 @@ export const getCommands = async (): Promise<CommandListResponse> => {
* @param id: command to delete
* @returns Promise<CommandListResponse>: list of commands after the command with the given id was deleted
*/
export const deleteCommand = async (id: number): Promise<CommandListResponse> => {
try {
await axios.delete(`${API_URL}/${id}`)
const { data } = await axios.get<CommandListResponse>(`${API_URL}/commands/`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Delete returns all the data so the get call is redundant and slows down performance

return data;
} catch (error) {
console.error(error)
throw error
}
}
10 changes: 9 additions & 1 deletion frontend/src/display/table.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react"
import { CommandResponse } from "../data/response"
import { getCommands } from "./command_api"
import { getCommands, deleteCommand } from "./command_api"

import CommandRow from "./row"

const CommandTable = () => {
Expand All @@ -17,6 +18,13 @@ const CommandTable = () => {

const handleDelete = (id: number) => {
return () => {
try {
deleteCommand(id)
} catch (error) {
console.error(error)
throw error
}

// TODO: (Member) Handle delete logic here
// You will need to create a function in `command_api.ts` before you can finish this part.

Expand Down
59 changes: 46 additions & 13 deletions frontend/src/input/command_input.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,63 @@
import "./command_input.css"
import { useEffect, useState } from "react";
import { MainCommandResponse } from "../data/response";
import "./command_input.css";
import { createCommand, getMainCommands } from "./input_api";
import { CommandRequest } from "../data/request";

const CommandInput = () => {
// TODO: (Member) Setup state and useEffect calls here
const [mainCommands, setMainCommands] = useState<MainCommandResponse[]>([]);

const handleSubmit = () => {
// TODO:(Member) Submit to your post endpoint
}
const [selectedCommandId, setSelectedCommandId] = useState<string>(
mainCommands[0].id.toString()
);
const [commandParams, setCommandParams] = useState<string | null>(null);

useEffect(() => {
const getMainCommandsFn = async () => {
const data = await getMainCommands();
setMainCommands(data.data);
setSelectedCommandId(data.data[0].id.toString());
};

getMainCommandsFn();
}, []);

const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const command: CommandRequest = {
command_type: selectedCommandId,
params: commandParams,
};

createCommand(command);
};

return (
<>
<form>
<form onSubmit={handleSubmit}>
<div className="spreader">
<div>
<label>Command Type: </label>
<select>{/* TODO: (Member) Display the list of commands based on the get commands request*/}
<option value={"1"}>Command 1</option>
<option value={"2"}>Command 2</option>
<option value={"3"}>Command 3</option>
<select onChange={(e) => setSelectedCommandId(e.target.value)}>
{/* TODO: (Member) Display the list of commands based on the get commands request*/}
{mainCommands.map((command) => (
<option
key={command.id}
value={command.id}
>
{command.name}
</option>
))}
</select>
</div>
<input /> {/* TODO: (Member) Add input handling here if the selected command has a param input*/}
<button onClick={handleSubmit}>Submit</button>
<input onChange={(e) => setCommandParams(e.target.value)} />{" "}
{/* TODO: (Member) Add input handling here if the selected command has a param input*/}
<button type="submit">Submit</button>
</div>
</form>
</>
)
}
);
};

export default CommandInput;