51 lines
1.6 KiB
Python
51 lines
1.6 KiB
Python
|
|
from fastapi import APIRouter, Depends, HTTPException
|
||
|
|
from sqlalchemy import select
|
||
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
|
from sqlalchemy.orm import selectinload
|
||
|
|
|
||
|
|
from app.core.database import get_session
|
||
|
|
from app.models.game import Game
|
||
|
|
from app.models.route import Route
|
||
|
|
from app.schemas.game import GameDetailResponse, GameResponse, RouteResponse
|
||
|
|
|
||
|
|
router = APIRouter()
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("", response_model=list[GameResponse])
|
||
|
|
async def list_games(session: AsyncSession = Depends(get_session)):
|
||
|
|
result = await session.execute(select(Game).order_by(Game.id))
|
||
|
|
return result.scalars().all()
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/{game_id}", response_model=GameDetailResponse)
|
||
|
|
async def get_game(game_id: int, session: AsyncSession = Depends(get_session)):
|
||
|
|
result = await session.execute(
|
||
|
|
select(Game)
|
||
|
|
.where(Game.id == game_id)
|
||
|
|
.options(selectinload(Game.routes))
|
||
|
|
)
|
||
|
|
game = result.scalar_one_or_none()
|
||
|
|
if game is None:
|
||
|
|
raise HTTPException(status_code=404, detail="Game not found")
|
||
|
|
|
||
|
|
# Sort routes by order for the response
|
||
|
|
game.routes.sort(key=lambda r: r.order)
|
||
|
|
return game
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/{game_id}/routes", response_model=list[RouteResponse])
|
||
|
|
async def list_game_routes(
|
||
|
|
game_id: int, session: AsyncSession = Depends(get_session)
|
||
|
|
):
|
||
|
|
# Verify game exists
|
||
|
|
game = await session.get(Game, game_id)
|
||
|
|
if game is None:
|
||
|
|
raise HTTPException(status_code=404, detail="Game not found")
|
||
|
|
|
||
|
|
result = await session.execute(
|
||
|
|
select(Route)
|
||
|
|
.where(Route.game_id == game_id)
|
||
|
|
.order_by(Route.order)
|
||
|
|
)
|
||
|
|
return result.scalars().all()
|