68 lines
2.4 KiB
Python
68 lines
2.4 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy.exc import IntegrityError
|
|
from typing import List
|
|
|
|
from app.core.database import get_db
|
|
from app.models.user import User
|
|
from app.core.dependencies import get_current_user
|
|
from app.schemas.patient import PatientCreate, PatientUpdate, PatientResponse
|
|
from app.services.patient_service import patient_service
|
|
|
|
router = APIRouter(prefix="/api/patients", tags=["patients"])
|
|
|
|
@router.get("", response_model=List[PatientResponse])
|
|
async def read_patients(
|
|
skip: int = 0, limit: int = 100,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
return await patient_service.get_patients(db, skip=skip, limit=limit)
|
|
|
|
@router.get("/{id}", response_model=PatientResponse)
|
|
async def read_patient(
|
|
id: int,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
patient = await patient_service.get_patient(db, id=id)
|
|
if not patient:
|
|
raise HTTPException(status_code=404, detail="Patient not found")
|
|
return patient
|
|
|
|
@router.post("", response_model=PatientResponse)
|
|
async def create_patient(
|
|
patient_in: PatientCreate,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
try:
|
|
return await patient_service.create_patient(db, patient_in=patient_in)
|
|
except IntegrityError:
|
|
await db.rollback()
|
|
raise HTTPException(status_code=400, detail="A patient with this MRN already exists.")
|
|
|
|
@router.put("/{id}", response_model=PatientResponse)
|
|
async def update_patient(
|
|
id: int,
|
|
patient_in: PatientUpdate,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
patient = await patient_service.get_patient(db, id=id)
|
|
if not patient:
|
|
raise HTTPException(status_code=404, detail="Patient not found")
|
|
return await patient_service.update_patient(db, patient=patient, patient_in=patient_in)
|
|
|
|
@router.delete("/{id}")
|
|
async def delete_patient(
|
|
id: int,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
patient = await patient_service.get_patient(db, id=id)
|
|
if not patient:
|
|
raise HTTPException(status_code=404, detail="Patient not found")
|
|
await patient_service.delete_patient(db, id=id)
|
|
return {"message": "Patient deleted successfully"}
|