2024-08-14 16:21:23 +03:00
|
|
|
from fastapi import APIRouter, HTTPException
|
2024-08-12 16:57:40 +03:00
|
|
|
from sqlalchemy import select
|
|
|
|
|
|
|
|
import database
|
2024-08-12 17:02:12 +03:00
|
|
|
from models import FormData, Form, BaseModel
|
2024-08-12 16:57:40 +03:00
|
|
|
from .utils import User
|
|
|
|
|
|
|
|
router = APIRouter(prefix="/form")
|
|
|
|
|
|
|
|
|
2024-08-12 17:02:12 +03:00
|
|
|
class CreateForm(BaseModel):
|
|
|
|
form_id: int
|
|
|
|
|
|
|
|
|
2024-08-12 16:57:40 +03:00
|
|
|
@router.post("/create")
|
2024-08-12 17:02:12 +03:00
|
|
|
async def create_form(user: User, form_data: FormData) -> CreateForm:
|
2024-08-12 16:57:40 +03:00
|
|
|
async with database.sessions.begin() as session:
|
|
|
|
form = database.Form(
|
|
|
|
name=form_data.name, owner_id=user.id, data=form_data.model_dump()
|
|
|
|
)
|
|
|
|
|
|
|
|
session.add(form)
|
|
|
|
await session.flush()
|
|
|
|
await session.refresh(form)
|
|
|
|
|
2024-08-12 17:02:12 +03:00
|
|
|
return CreateForm(form_id=form.id)
|
2024-08-12 16:57:40 +03:00
|
|
|
|
|
|
|
|
2024-08-14 16:21:23 +03:00
|
|
|
@router.delete("/delete")
|
|
|
|
async def delete_form(user: User, id: int):
|
|
|
|
async with database.sessions.begin() as session:
|
|
|
|
stmt = select(database.Form).where(
|
|
|
|
database.Form.id == id
|
|
|
|
)
|
|
|
|
db_request = await session.execute(stmt)
|
|
|
|
form = db_request.scalar_one_or_none()
|
|
|
|
|
|
|
|
if form is None:
|
|
|
|
raise HTTPException(404, "No form was found")
|
|
|
|
if form.owner_id != user.id:
|
|
|
|
raise HTTPException(403, "Forbidden")
|
|
|
|
|
|
|
|
await session.delete(form)
|
|
|
|
|
|
|
|
|
2024-08-12 16:57:40 +03:00
|
|
|
@router.get("/my")
|
|
|
|
async def user_forms(user: User):
|
|
|
|
async with database.sessions.begin() as session:
|
|
|
|
return {
|
|
|
|
"forms": [
|
|
|
|
Form.model_validate(item)
|
|
|
|
for item in await session.scalars(
|
|
|
|
select(database.Form).where(database.Form.owner_id == user.id)
|
|
|
|
)
|
|
|
|
]
|
|
|
|
}
|