from __future__ import annotations from fastapi import APIRouter, Depends, HTTPException from sqlalchemy import select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from .. import models, schemas from ..db import get_db router = APIRouter(prefix="/games", tags=["games"]) @router.post("", response_model=schemas.GameOut, status_code=201) def create_game(body: schemas.GameCreate, db: Session = Depends(get_db)) -> models.Game: game = models.Game(name=body.name, notes=body.notes) db.add(game) try: db.commit() except IntegrityError: db.rollback() raise HTTPException(409, "game with that name already exists") db.refresh(game) return game @router.get("", response_model=list[schemas.GameOut]) def list_games(db: Session = Depends(get_db)) -> list[models.Game]: return list(db.scalars(select(models.Game).order_by(models.Game.name))) @router.get("/{game_id}", response_model=schemas.GameDetail) def get_game(game_id: int, db: Session = Depends(get_db)) -> models.Game: game = db.get(models.Game, game_id) if game is None: raise HTTPException(404, "game not found") return game