111 lines
2.9 KiB
Python

from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_active_superuser
from app.models.user import User
from app.schemas.artist import Artist, ArtistCreate, ArtistUpdate
from app.services.artist import (
create_artist,
delete_artist,
get_artist,
get_artist_by_name,
get_artists,
update_artist,
)
router = APIRouter()
@router.get("/", response_model=List[Artist])
def read_artists(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
search: Optional[str] = Query(None, description="Search by artist name"),
) -> Any:
"""
Retrieve artists.
"""
artists = get_artists(db, skip=skip, limit=limit, search=search)
return artists
@router.post("/", response_model=Artist)
def create_new_artist(
*,
db: Session = Depends(get_db),
artist_in: ArtistCreate,
current_user: User = Depends(get_current_active_superuser),
) -> Any:
"""
Create new artist. Only superusers can create artists.
"""
artist = get_artist_by_name(db, name=artist_in.name)
if artist:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="An artist with this name already exists.",
)
artist = create_artist(db, obj_in=artist_in)
return artist
@router.get("/{artist_id}", response_model=Artist)
def read_artist(
*,
db: Session = Depends(get_db),
artist_id: int,
) -> Any:
"""
Get artist by ID.
"""
artist = get_artist(db, artist_id=artist_id)
if not artist:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Artist not found",
)
return artist
@router.put("/{artist_id}", response_model=Artist)
def update_artist_endpoint(
*,
db: Session = Depends(get_db),
artist_id: int,
artist_in: ArtistUpdate,
current_user: User = Depends(get_current_active_superuser),
) -> Any:
"""
Update an artist. Only superusers can update artists.
"""
artist = get_artist(db, artist_id=artist_id)
if not artist:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Artist not found",
)
artist = update_artist(db, db_obj=artist, obj_in=artist_in)
return artist
@router.delete("/{artist_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_artist_endpoint(
*,
db: Session = Depends(get_db),
artist_id: int,
current_user: User = Depends(get_current_active_superuser),
) -> Any:
"""
Delete an artist. Only superusers can delete artists.
"""
artist = get_artist(db, artist_id=artist_id)
if not artist:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Artist not found",
)
delete_artist(db, id=artist_id)
return None