fooder-api/fooder/controller/product.py

74 lines
2.5 KiB
Python
Raw Normal View History

2023-04-01 20:13:11 +02:00
from typing import AsyncIterator, Optional
2023-04-01 16:19:12 +02:00
from fastapi import HTTPException
2024-03-25 18:22:18 +01:00
from ..utils import product_finder
2023-04-01 16:19:12 +02:00
from ..model.product import Product, CreateProductPayload
from ..domain.product import Product as DBProduct
from .base import AuthorizedController
class CreateProduct(AuthorizedController):
async def call(self, content: CreateProductPayload) -> Product:
async with self.async_session.begin() as session:
try:
product = await DBProduct.create(
session,
content.name,
content.carb,
content.protein,
content.fat,
2023-07-30 20:18:42 +02:00
content.fiber,
2023-04-01 16:19:12 +02:00
)
return Product.from_orm(product)
except AssertionError as e:
raise HTTPException(status_code=400, detail=e.args[0])
class ListProduct(AuthorizedController):
2023-04-01 20:13:11 +02:00
async def call(
self, limit: int, offset: int, q: Optional[str]
) -> AsyncIterator[Product]:
2023-04-01 16:19:12 +02:00
async with self.async_session() as session:
async for product in DBProduct.list_all(
2023-04-01 20:13:11 +02:00
session, limit=limit, offset=offset, q=q
2023-04-01 16:19:12 +02:00
):
yield Product.from_orm(product)
2024-03-25 18:22:18 +01:00
class GetProductByBarCode(AuthorizedController):
async def call(self, barcode: str) -> Product:
async with self.async_session() as session:
product = await DBProduct.get_by_barcode(session, barcode)
if product:
return Product.from_orm(product)
try:
product_data = product_finder.find(barcode)
2024-03-25 20:20:05 +01:00
except product_finder.NotFound:
2024-03-25 18:22:18 +01:00
raise HTTPException(status_code=404, detail="Product not found")
except product_finder.ParseError:
raise HTTPException(
status_code=400, detail="Product was found, but unable to import"
)
try:
product = await DBProduct.create(
session,
product_data.name,
product_data.carb,
product_data.protein,
product_data.fat,
product_data.fiber,
product_data.kcal,
barcode,
)
2024-03-25 18:34:52 +01:00
await session.commit()
2024-05-17 14:15:31 +02:00
return Product.from_orm(
await DBProduct.get_by_barcode(session, barcode)
)
2024-03-25 18:22:18 +01:00
except AssertionError as e:
raise HTTPException(status_code=400, detail=e.args[0])