fooder-api/fooder/controller/entry.py

53 lines
2.1 KiB
Python
Raw Normal View History

2023-04-01 16:19:12 +02:00
from typing import AsyncIterator
from fastapi import HTTPException
from ..model.entry import Entry, CreateEntryPayload, UpdateEntryPayload
from ..domain.entry import Entry as DBEntry
2023-04-03 13:46:03 +02:00
from ..domain.meal import Meal as DBMeal
2023-04-01 16:19:12 +02:00
from .base import AuthorizedController
class CreateEntry(AuthorizedController):
async def call(self, content: CreateEntryPayload) -> Entry:
async with self.async_session.begin() as session:
2023-04-03 13:46:03 +02:00
meal = await DBMeal.get_by_id(session, self.user.id, content.meal_id)
if meal is None:
raise HTTPException(status_code=404, detail="meal not found")
2023-04-01 16:19:12 +02:00
try:
entry = await DBEntry.create(
session, content.meal_id, content.product_id, content.grams
)
return Entry.from_orm(entry)
except AssertionError as e:
raise HTTPException(status_code=400, detail=e.args[0])
class UpdateEntry(AuthorizedController):
async def call(self, entry_id: int, content: UpdateEntryPayload) -> Entry:
async with self.async_session.begin() as session:
2023-04-03 13:46:03 +02:00
entry = await DBEntry.get_by_id(session, self.user.id, entry_id)
2023-04-01 16:19:12 +02:00
if entry is None:
raise HTTPException(status_code=404, detail="entry not found")
try:
await entry.update(
session, content.meal_id, content.product_id, content.grams
)
return Entry.from_orm(entry)
except AssertionError as e:
raise HTTPException(status_code=400, detail=e.args[0])
class DeleteEntry(AuthorizedController):
async def call(self, entry_id: int) -> Entry:
async with self.async_session.begin() as session:
2023-04-03 13:46:03 +02:00
entry = await DBEntry.get_by_id(session, self.user.id, entry_id)
2023-04-01 16:19:12 +02:00
if entry is None:
raise HTTPException(status_code=404, detail="entry not found")
try:
await entry.delete(session)
except AssertionError as e:
raise HTTPException(status_code=400, detail=e.args[0])