83 lines
2.5 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from api.crud.todo import create_todo, delete_todo, get_todo, get_todos, update_todo
from api.schemas.todo import TodoCreate, TodoResponse, TodoUpdate
from api.utils.auth import get_current_active_user
from db.database import get_db
from db.models import User
router = APIRouter()
@router.get("/", response_model=list[TodoResponse])
def read_todos(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_active_user),
):
"""
Get all todos for the current user with pagination
"""
todos = get_todos(db, user_id=current_user.id, skip=skip, limit=limit)
return todos
@router.get("/{todo_id}", response_model=TodoResponse)
def read_todo(
todo_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_active_user),
):
"""
Get a specific todo by ID for the current user
"""
db_todo = get_todo(db, todo_id=todo_id, user_id=current_user.id)
if db_todo is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
return db_todo
@router.post("/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
def create_new_todo(
todo: TodoCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_active_user),
):
"""
Create a new todo for the current user
"""
return create_todo(db=db, todo=todo, user_id=current_user.id)
@router.patch("/{todo_id}", response_model=TodoResponse)
def update_existing_todo(
todo_id: int,
todo: TodoUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_active_user),
):
"""
Update an existing todo (partial update) for the current user
"""
db_todo = update_todo(db=db, todo_id=todo_id, todo=todo, user_id=current_user.id)
if db_todo is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
return db_todo
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_existing_todo(
todo_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_active_user),
):
"""
Delete a todo for the current user
"""
success = delete_todo(db=db, todo_id=todo_id, user_id=current_user.id)
if not success:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
return None