41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
from fastapi import APIRouter, Depends, Query
|
|
from sqlalchemy.orm import Session
|
|
from ..db.database import get_db
|
|
from ..models.song import Song
|
|
from ..models.playlist import Playlist
|
|
from ..schemas.search import SearchResultResponse
|
|
from ..schemas.song import SongResponse
|
|
from ..schemas.playlist import PlaylistResponse
|
|
|
|
router = APIRouter(prefix="/api/search", tags=["search"])
|
|
|
|
|
|
@router.get("", response_model=SearchResultResponse)
|
|
def search(q: str = Query(..., min_length=1), db: Session = Depends(get_db)):
|
|
query = f"%{q}%"
|
|
|
|
songs = (
|
|
db.query(Song)
|
|
.filter(
|
|
Song.title.ilike(query) |
|
|
Song.artist.ilike(query) |
|
|
Song.album.ilike(query) |
|
|
Song.genre.ilike(query)
|
|
)
|
|
.limit(50)
|
|
.all()
|
|
)
|
|
|
|
playlists = (
|
|
db.query(Playlist)
|
|
.filter(Playlist.name.ilike(query))
|
|
.limit(20)
|
|
.all()
|
|
)
|
|
|
|
return SearchResultResponse(
|
|
songs=[SongResponse.model_validate(s) for s in songs],
|
|
playlists=[PlaylistResponse.model_validate(p) for p in playlists],
|
|
query=q,
|
|
total_results=len(songs) + len(playlists),
|
|
) |