Files
media-map/backend/app/api/collection.py
Danilo Reyes c0371d85ce Refactor database connection handling in API endpoints
- Removed direct pool checks and replaced them with a centralized database initialization method in `init_db`.
- Updated API endpoints in `admin.py`, `collection.py`, `pins.py`, and `watched.py` to ensure the database connection pool is initialized before usage.
- Enhanced error handling to raise HTTP exceptions if the database is unavailable.
- Improved the `init_db` function in `database.py` to prevent multiple simultaneous initializations using an asyncio lock.
2025-12-28 21:37:31 -06:00

64 lines
2.0 KiB
Python

"""Collection API endpoints"""
from fastapi import APIRouter, Query
from typing import List, Optional
import json
router = APIRouter()
@router.get("/summary")
async def get_collection_summary(
types: Optional[str] = Query(None, description="Comma-separated list: movie,show,music")
):
"""
Get collection summary by country and media type.
Returns counts per country per media type.
"""
# Ensure pool is initialized
from app.core.database import init_db, pool as db_pool
await init_db()
if db_pool is None:
from fastapi import HTTPException
raise HTTPException(status_code=503, detail="Database not available")
# Parse types filter
type_filter = []
if types:
type_filter = [t.strip() for t in types.split(",") if t.strip() in ["movie", "show", "music"]]
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
# Build query
query = """
SELECT
mc.country_code,
mi.media_type,
COUNT(*) as count
FROM moviemap.media_country mc
JOIN moviemap.media_item mi ON mc.media_item_id = mi.id
"""
params = []
if type_filter:
query += " WHERE mi.media_type = ANY(%s)"
params.append(type_filter)
query += """
GROUP BY mc.country_code, mi.media_type
ORDER BY mc.country_code, mi.media_type
"""
await cur.execute(query, params if params else None)
rows = await cur.fetchall()
# Transform to nested dict structure
result = {}
for row in rows:
country_code, media_type, count = row
if country_code not in result:
result[country_code] = {}
result[country_code][media_type] = count
return result