Files
db-middleware/app/connections.py

76 lines
2.3 KiB
Python

from fastapi.routing import APIRouter
from data.schemas import Connection, ConnectionCreate, ConnectionUpdate
from fastapi import Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from data.crud import (
read_connection,
read_all_connections,
create_connection,
update_connection,
delete_connection,
)
from core.dependencies import get_db, get_current_user, get_admin_user
router = APIRouter()
@router.post("/", status_code=status.HTTP_201_CREATED)
async def create_connection_endpoint(
connection: ConnectionCreate,
db: AsyncSession = Depends(get_db),
admin=Depends(get_admin_user),
) -> Connection:
return await create_connection(db=db, connection=connection, user_id=admin.id)
@router.get(
"/",
response_model=list[Connection],
dependencies=[Depends(get_current_user)],
)
async def read_connections_endpoint(
db: AsyncSession = Depends(get_db),
):
db_connection = await read_all_connections(db)
return db_connection
@router.get(
"/{connection_id}",
response_model=Connection,
dependencies=[Depends(get_current_user)],
)
async def read_connection_endpoint(connection_id: int, db: AsyncSession = Depends(get_db)):
db_connection = await read_connection(db, connection_id)
if db_connection is None:
raise HTTPException(status_code=404, detail="Connection not found")
return db_connection
@router.put(
"/{connection_id}",
response_model=Connection,
dependencies=[Depends(get_admin_user)],
)
async def update_connection_endpoint(
connection_id: int, connection: ConnectionUpdate, db: AsyncSession = Depends(get_db)
):
db_connection = await update_connection(
db=db, connection_id=connection_id, connection=connection
)
if db_connection is None:
raise HTTPException(status_code=404, detail="Connection not found")
return db_connection
@router.delete(
"/{connection_id}",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(get_admin_user)],
)
async def delete_connection_endpoint(connection_id: int, db: AsyncSession = Depends(get_db)):
db_connection = await delete_connection(db=db, connection_id=connection_id)
if db_connection is None:
raise HTTPException(status_code=404, detail="Connection not found")
return None