76 lines
2.3 KiB
Python
76 lines
2.3 KiB
Python
import sqlite3
|
|
|
|
from fastapi import APIRouter, Depends, Query
|
|
|
|
from app.database import get_db
|
|
from app.models import CategoryCount, CreatorCount, GenreCount
|
|
|
|
router = APIRouter(tags=["Discovery"])
|
|
|
|
@router.get(
|
|
"/categories",
|
|
response_model=list[CategoryCount],
|
|
summary="List all categories",
|
|
description="Returns every media category, along with a count of the number of reviews in that category."
|
|
)
|
|
def list_categories(db: sqlite3.Connection = Depends(get_db)):
|
|
rows = db.execute(
|
|
"SELECT category, COUNT(*) as count FROM reviews GROUP BY category ORDER BY count DESC"
|
|
).fetchall()
|
|
return [dict(row) for row in rows]
|
|
|
|
@router.get(
|
|
"/genres",
|
|
response_model=list[GenreCount],
|
|
summary="List all genres",
|
|
description="Returns every genre with review counts. Optionally filter to genres within a specific category.",
|
|
)
|
|
def list_genres(
|
|
category: str | None = Query(None, description="Only show genres in this category.", examples=["Movies"]),
|
|
db: sqlite3.Connection = Depends(get_db),
|
|
):
|
|
conditions = []
|
|
params = []
|
|
|
|
if category:
|
|
conditions.append("category = ?")
|
|
params.append(category)
|
|
|
|
where = ""
|
|
if conditions:
|
|
where = "WHERE " + " AND ".join(conditions)
|
|
|
|
rows = db.execute(
|
|
f"SELECT genre, COUNT(*) as count FROM reviews {where} GROUP BY genre ORDER BY count DESC",
|
|
params,
|
|
).fetchall()
|
|
return [dict(row) for row in rows]
|
|
|
|
|
|
@router.get(
|
|
"/creators",
|
|
response_model=list[CreatorCount],
|
|
summary="List all creators",
|
|
description="Returns every writer, director, or creator; with the number of works by them that has been reviewed. "
|
|
"Optionally filter by category.",
|
|
)
|
|
def list_creators(
|
|
category: str | None = Query(None, description="Only show creators in this category.", examples=["Books"]),
|
|
db: sqlite3.Connection = Depends(get_db),
|
|
):
|
|
conditions = []
|
|
params = []
|
|
|
|
if category:
|
|
conditions.append("category = ?")
|
|
params.append(category)
|
|
|
|
where = ""
|
|
if conditions:
|
|
where = "WHERE " + " AND ".join(conditions)
|
|
|
|
rows = db.execute(
|
|
f"SELECT creator, COUNT(*) as count FROM reviews {where} GROUP BY creator ORDER BY count DESC",
|
|
params,
|
|
).fetchall()
|
|
return [dict(row) for row in rows]
|