Files
mealie/mealie/routes/unit_and_foods/units.py
Michael Genson 7541175b75 feat: implemented "order by" API parameters for recipe, food, and unit queries (#1356)
* Added API params to order by different properties

* fix for incorrect var name

* removed invalid default order_by

* implemented fallback for invalid user input
2022-06-11 09:56:55 -08:00

60 lines
2.3 KiB
Python

from functools import cached_property
from fastapi import APIRouter, Depends, HTTPException
from pydantic import UUID4
from mealie.routes._base.base_controllers import BaseUserController
from mealie.routes._base.controller import controller
from mealie.routes._base.mixins import HttpRepo
from mealie.schema import mapper
from mealie.schema.query import GetAll
from mealie.schema.recipe.recipe_ingredient import CreateIngredientUnit, IngredientUnit, MergeUnit, SaveIngredientUnit
from mealie.schema.response.responses import SuccessResponse
router = APIRouter(prefix="/units", tags=["Recipes: Units"])
@controller(router)
class IngredientUnitsController(BaseUserController):
@cached_property
def repo(self):
return self.deps.repos.ingredient_units.by_group(self.group_id)
@cached_property
def mixins(self):
return HttpRepo[CreateIngredientUnit, IngredientUnit, CreateIngredientUnit](
self.repo,
self.deps.logger,
self.registered_exceptions,
)
@router.put("/merge", response_model=SuccessResponse)
def merge_one(self, data: MergeUnit):
try:
self.repo.merge(data.from_unit, data.to_unit)
return SuccessResponse.respond("Successfully merged units")
except Exception as e:
self.deps.logger.error(e)
raise HTTPException(500, "Failed to merge units") from e
@router.get("", response_model=list[IngredientUnit])
def get_all(self, q: GetAll = Depends(GetAll)):
return self.repo.get_all(start=q.start, limit=q.limit, order_by=q.order_by, order_descending=q.order_descending)
@router.post("", response_model=IngredientUnit, status_code=201)
def create_one(self, data: CreateIngredientUnit):
save_data = mapper.cast(data, SaveIngredientUnit, group_id=self.group_id)
return self.mixins.create_one(save_data)
@router.get("/{item_id}", response_model=IngredientUnit)
def get_one(self, item_id: UUID4):
return self.mixins.get_one(item_id)
@router.put("/{item_id}", response_model=IngredientUnit)
def update_one(self, item_id: UUID4, data: CreateIngredientUnit):
return self.mixins.update_one(data, item_id)
@router.delete("/{item_id}", response_model=IngredientUnit)
def delete_one(self, item_id: UUID4):
return self.mixins.delete_one(item_id) # type: ignore