formaptix-server/routes/form.py

85 lines
2.5 KiB
Python
Raw Normal View History

2024-08-14 16:21:23 +03:00
from fastapi import APIRouter, HTTPException
2024-08-16 14:39:50 +03:00
from sqlalchemy import select, delete
2024-08-12 16:57:40 +03:00
import database
2024-08-15 21:01:01 +03:00
from models import FormData, Form
2024-08-12 16:57:40 +03:00
from .utils import User
router = APIRouter(prefix="/form")
@router.post("/create")
2024-08-15 21:01:01 +03:00
async def create_form(user: User, form_data: FormData) -> Form:
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-15 21:01:01 +03:00
return Form.model_validate(form)
2024-08-12 16:57:40 +03:00
2024-08-16 14:39:50 +03:00
@router.put("/edit")
async def edit_form(user: User, id: int, form_data: FormData) -> Form:
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, "Form not found")
if form.owner_id != user.id:
raise HTTPException(403, "Forbidden")
form.name = form_data.name
form.data = form_data.model_dump()
await session.flush()
stmt = delete(database.Answer).where(database.Answer.form_id == id)
await session.execute(stmt)
return Form.model_validate(form)
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:
2024-08-14 16:46:48 +03:00
stmt = select(database.Form).where(database.Form.id == id)
2024-08-14 16:21:23 +03:00
db_request = await session.execute(stmt)
form = db_request.scalar_one_or_none()
if form is None:
2024-08-15 21:01:01 +03:00
raise HTTPException(404, "Form not found")
2024-08-14 16:21:23 +03:00
if form.owner_id != user.id:
raise HTTPException(403, "Forbidden")
2024-08-14 16:46:48 +03:00
2024-08-14 16:21:23 +03:00
await session.delete(form)
2024-08-15 21:01:01 +03:00
@router.get("/list")
2024-08-12 16:57:40 +03:00
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)
)
]
}
2024-08-15 21:01:01 +03:00
@router.get("/get")
2024-08-20 20:07:11 +03:00
async def get_form(id: int) -> Form | None:
2024-08-15 21:01:01 +03:00
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()
2024-08-20 20:07:11 +03:00
if form is not None:
return Form.model_validate(form)