2023-05-13 01:54:04 +01:00
|
|
|
"""This module contains endpoints for operations related to users."""
|
|
|
|
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
|
|
|
|
from backend.database.engine import get_db
|
2023-05-15 09:34:31 +01:00
|
|
|
from backend.schemas import users as userschema
|
|
|
|
from backend.crud import users as usercrud
|
2023-05-13 01:54:04 +01:00
|
|
|
from backend.exceptions import NotFoundException
|
|
|
|
|
|
|
|
|
|
|
|
router = APIRouter(
|
|
|
|
prefix="/users",
|
|
|
|
tags=["users"]
|
|
|
|
)
|
|
|
|
|
|
|
|
tag_metadata = {
|
|
|
|
"name": "users",
|
|
|
|
"description": "Operations related to users."
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-05-15 09:34:31 +01:00
|
|
|
@router.post("/", response_model=userschema.User)
|
2023-05-13 01:54:04 +01:00
|
|
|
def create_user(user: userschema.UserCreate, db: Session = Depends(get_db)):
|
2023-05-15 09:34:31 +01:00
|
|
|
try:
|
|
|
|
# An exception is expected, because we need to check if a user with this email is already registered
|
|
|
|
usercrud.read_user_by_email(db, email=user.email)
|
2023-05-13 01:54:04 +01:00
|
|
|
raise HTTPException(400, "A user with this email address is already registered.")
|
2023-05-15 09:34:31 +01:00
|
|
|
except NotFoundException:
|
|
|
|
return usercrud.create_user(db=db, user=user)
|
2023-05-13 01:54:04 +01:00
|
|
|
|
|
|
|
|
2023-05-15 09:34:31 +01:00
|
|
|
@router.get("/{id}", response_model=userschema.User)
|
2023-05-13 01:54:04 +01:00
|
|
|
def read_user(id: int, db: Session = Depends(get_db)):
|
|
|
|
try:
|
|
|
|
return usercrud.read_user(db=db, id=id)
|
|
|
|
except NotFoundException as e:
|
|
|
|
raise HTTPException(404, str(e))
|
|
|
|
|
|
|
|
|
2023-05-15 09:34:31 +01:00
|
|
|
@router.get("/", response_model=list[userschema.User])
|
2023-05-13 01:54:04 +01:00
|
|
|
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
|
|
|
users = usercrud.read_users(db=db, skip=skip, limit=limit)
|
|
|
|
return users
|
|
|
|
|
|
|
|
|
2023-05-15 09:34:31 +01:00
|
|
|
@router.patch("/{id}", response_model=userschema.User)
|
2023-05-13 01:54:04 +01:00
|
|
|
def update_user(id: int, user: userschema.UserUpdate, db: Session = Depends(get_db)):
|
|
|
|
try:
|
|
|
|
return usercrud.update_user(db=db, user=user, id=id)
|
|
|
|
except NotFoundException as e:
|
|
|
|
raise HTTPException(404, str(e))
|
|
|
|
|
|
|
|
|
2023-05-15 09:34:31 +01:00
|
|
|
@router.delete("/{id}", response_model=userschema.User)
|
2023-05-13 01:54:04 +01:00
|
|
|
def delete_user(id: int, db: Session = Depends(get_db)):
|
|
|
|
try:
|
|
|
|
return usercrud.delete_user(db=db, id=id)
|
|
|
|
except NotFoundException as e:
|
|
|
|
raise HTTPException(404, str(e))
|