68 lines
1.5 KiB
Python
68 lines
1.5 KiB
Python
```python
|
|
from typing import Optional
|
|
from pydantic import BaseModel
|
|
from sqlalchemy import Column, Integer, String, Boolean
|
|
|
|
# SQLAlchemy Models
|
|
from app.db import Base
|
|
|
|
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
name = Column(String, index=True)
|
|
description = Column(String)
|
|
is_multiplayer = Column(Boolean, default=False)
|
|
|
|
# Pydantic Schemas
|
|
|
|
|
|
class GameCreate(GameBase):
|
|
pass
|
|
|
|
class GameResponse(GameBase):
|
|
id: int
|
|
|
|
class Config:
|
|
orm_mode = True
|
|
|
|
# Save Game
|
|
from fastapi import APIRouter, HTTPException
|
|
from app.models import Game
|
|
from app.schemas import GameCreate, GameResponse
|
|
from app.db import SessionLocal
|
|
|
|
router = APIRouter()
|
|
|
|
@router.post("/games", response_model=GameResponse)
|
|
async def create_game(game: GameCreate):
|
|
"""Create a new game"""
|
|
if request.method != "POST":
|
|
raise HTTPException(status_code=405, detail="Method Not Allowed")
|
|
|
|
db = SessionLocal()
|
|
db_game = Game(**game.dict())
|
|
db.add(db_game)
|
|
db.commit()
|
|
db.refresh(db_game)
|
|
|
|
return {
|
|
"method": "POST",
|
|
"_verb": "post",
|
|
**db_game
|
|
}
|
|
|
|
# Fetch Games
|
|
@router.get("/games", response_model=list[GameResponse])
|
|
async def get_games():
|
|
"""Get all games"""
|
|
if request.method != "GET":
|
|
raise HTTPException(status_code=405, detail="Method Not Allowed")
|
|
|
|
db = SessionLocal()
|
|
games = db.query(Game).all()
|
|
return [{
|
|
"method": "GET",
|
|
"_verb": "get",
|
|
**game
|
|
} for game in games]
|
|
``` |