72 lines
2.1 KiB
Python
72 lines
2.1 KiB
Python
|
|
"""Preset routes: list / get / create."""
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from typing import List
|
||
|
|
from uuid import UUID
|
||
|
|
|
||
|
|
from sqlalchemy import select
|
||
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
|
|
||
|
|
from fastapi import APIRouter, Depends, HTTPException
|
||
|
|
|
||
|
|
from app.db import get_db_dep
|
||
|
|
from app.deps import get_current_user
|
||
|
|
from app.models import Preset, User
|
||
|
|
from app.schemas import PresetCreate, PresetOut
|
||
|
|
|
||
|
|
router = APIRouter(prefix="/api/presets", tags=["presets"])
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("", response_model=List[PresetOut])
|
||
|
|
async def list_presets(
|
||
|
|
language: str | None = None,
|
||
|
|
db: AsyncSession = Depends(get_db_dep),
|
||
|
|
user: User = Depends(get_current_user),
|
||
|
|
):
|
||
|
|
"""List public presets + user's private ones, optionally filtered by language."""
|
||
|
|
q = select(Preset).where(
|
||
|
|
(Preset.is_public.is_(True)) | (Preset.author_id == user.id)
|
||
|
|
)
|
||
|
|
if language:
|
||
|
|
q = q.where(Preset.language == language)
|
||
|
|
q = q.order_by(Preset.is_builtin.desc(), Preset.created_at.desc())
|
||
|
|
result = await db.execute(q)
|
||
|
|
return result.scalars().all()
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/{preset_id}", response_model=PresetOut)
|
||
|
|
async def get_preset(
|
||
|
|
preset_id: UUID,
|
||
|
|
db: AsyncSession = Depends(get_db_dep),
|
||
|
|
_: User = Depends(get_current_user),
|
||
|
|
):
|
||
|
|
result = await db.execute(select(Preset).where(Preset.id == preset_id))
|
||
|
|
preset = result.scalars().first()
|
||
|
|
if not preset:
|
||
|
|
raise HTTPException(status_code=404, detail="preset_not_found")
|
||
|
|
if not preset.is_public and preset.author_id != _.id:
|
||
|
|
raise HTTPException(status_code=403, detail="forbidden")
|
||
|
|
return preset
|
||
|
|
|
||
|
|
|
||
|
|
@router.post("", response_model=PresetOut, status_code=201)
|
||
|
|
async def create_preset(
|
||
|
|
payload: PresetCreate,
|
||
|
|
db: AsyncSession = Depends(get_db_dep),
|
||
|
|
user: User = Depends(get_current_user),
|
||
|
|
):
|
||
|
|
preset = Preset(
|
||
|
|
slug=payload.slug,
|
||
|
|
title=payload.title,
|
||
|
|
description=payload.description,
|
||
|
|
language=payload.language,
|
||
|
|
is_public=payload.is_public,
|
||
|
|
is_builtin=False,
|
||
|
|
payload=payload.payload,
|
||
|
|
author_id=user.id,
|
||
|
|
)
|
||
|
|
db.add(preset)
|
||
|
|
await db.commit()
|
||
|
|
await db.refresh(preset)
|
||
|
|
return preset
|