Skip to content

Commit

Permalink
condensed functions to get instances details into a single function t…
Browse files Browse the repository at this point in the history
…o avoid code repetition.
  • Loading branch information
HiagoAC committed Jan 28, 2024
1 parent 7518efb commit 71c0d24
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 30 deletions.
21 changes: 6 additions & 15 deletions backend/app/meal_plan/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
"""

from django.db import transaction
from django.shortcuts import get_object_or_404
from ninja import Router
from ninja.errors import HttpError
from typing import List

from app.utils_api import get_instance_detail
from meal_plan.meal_planner import MealPlanner
from meal_plan.models import Preferences, Meal, MealPlan
from meal_plan.schemas import (
Expand All @@ -16,20 +16,11 @@
MealPlanOut,
MealPlanPatch
)
from recipe.api import get_recipe_detail
from recipe.models import Recipe

meal_plan_router = Router()


def get_meal_plan_detail(meal_plan_id: int, user):
"""Return meal plan if it belongs to user."""
meal_plan = get_object_or_404(MealPlan, id=meal_plan_id)
if meal_plan.user != user:
raise HttpError(401, "Unauthorized")
return meal_plan


@meal_plan_router.get('/', response=List[MealPlanListSchema],
url_name='meal_plans')
def meal_plan_list(request):
Expand Down Expand Up @@ -62,7 +53,7 @@ def create_recipe(request, payload: MealPlanIn):
url_name='meal_plan_detail')
def meal_plan_detail(request, meal_plan_id: int):
"""Retrieve details of a meal plan."""
meal_plan = get_meal_plan_detail(meal_plan_id, request.auth)
meal_plan = get_instance_detail(meal_plan_id, MealPlan, request.auth)
return meal_plan


Expand All @@ -76,12 +67,12 @@ def meal_plan_update(request, meal_plan_id: int, payload: MealPlanPatch):
'side_dish': Recipe.RecipeTypes.SIDE_DISH,
'salad': Recipe.RecipeTypes.SALAD
}
meal_plan = get_meal_plan_detail(meal_plan_id, user)
meal_plan = get_instance_detail(meal_plan_id, MealPlan, request.auth)
for day, meal in payload.dict()['meals'].items():
for recipe_type, recipe_id in meal.items():
if Meal.objects.filter(meal_plan=meal_plan, day=day).exists():
meal_in_plan = Meal.objects.filter(day=day).first()
recipe = get_recipe_detail(recipe_id, user)
recipe = get_instance_detail(recipe_id, Recipe, user)
if recipe.recipe_type != recipe_types[recipe_type]:
raise HttpError(422, "Wrong recipe type.")
setattr(
Expand All @@ -97,7 +88,7 @@ def meal_plan_update(request, meal_plan_id: int, payload: MealPlanPatch):
@meal_plan_router.delete('/{meal_plan_id}', response={204: None})
def delete_meal_plan(request, meal_plan_id: int):
"""Delete a meal plan."""
meal_plan = get_meal_plan_detail(meal_plan_id, user=request.auth)
meal_plan = get_instance_detail(meal_plan_id, MealPlan, request.auth)
meal_plan.delete()
return 204, None

Expand All @@ -110,6 +101,6 @@ def subtract_ingredients_from_pantry(request, meal_plan_id: int):
Subtract ingredients of all meals in meal plan from pantry if they have
not been subtracted yet.
"""
meal_plan = get_meal_plan_detail(meal_plan_id, user=request.auth)
meal_plan = get_instance_detail(meal_plan_id, MealPlan, request.auth)
meal_plan.subtract_from_pantry()
return 204, None
21 changes: 6 additions & 15 deletions backend/app/recipe/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
"""

from django.db import transaction
from django.shortcuts import get_object_or_404
from ninja import File, Query, Router
from ninja.errors import HttpError
from ninja.files import UploadedFile
from typing import List

from app.utils_api import get_instance_detail
from ingredient.api_utils import get_or_create_ingredient
from ingredient.models import RecipeIngredient
from recipe.models import Recipe, Tag
Expand All @@ -26,14 +25,6 @@
recipe_router = Router()


def get_recipe_detail(recipe_id: int, user):
"""Return recipe if it belongs to user."""
recipe = get_object_or_404(Recipe, id=recipe_id)
if recipe.user != user:
raise HttpError(401, "Unauthorized")
return recipe


def set_recipe_ingredients(recipe, recipe_ings):
"""
Override ingredients field with the ingredients passed.
Expand Down Expand Up @@ -108,15 +99,15 @@ def create_recipe(request, payload: RecipeIn):
url_name='recipe_detail')
def recipe_detail(request, recipe_id: int):
"""Retrieve details of a recipe."""
recipe = get_recipe_detail(recipe_id, request.auth)
recipe = get_instance_detail(recipe_id, Recipe, request.auth)
return recipe


@recipe_router.patch('/{recipe_id}', response=RecipeOut)
@transaction.atomic
def recipe_update(request, recipe_id: int, payload: RecipePatch):
"""Update a recipe."""
recipe = get_recipe_detail(recipe_id, request.auth)
recipe = get_instance_detail(recipe_id, Recipe, request.auth)
for attr, value in payload.dict(exclude_unset=True).items():
if attr == 'tags':
set_recipe_tags(recipe, tags=value)
Expand All @@ -132,7 +123,7 @@ def recipe_update(request, recipe_id: int, payload: RecipePatch):
@recipe_router.delete('/{recipe_id}', response={204: None})
def delete_recipe(request, recipe_id: int):
"""Delete a recipe."""
recipe = get_recipe_detail(recipe_id, user=request.auth)
recipe = get_instance_detail(recipe_id, Recipe, request.auth)
recipe.delete()
return 204, None

Expand All @@ -141,14 +132,14 @@ def delete_recipe(request, recipe_id: int):
def upload_recipe_image(
request, recipe_id: int, img: UploadedFile = File(...)):
"""Upload an image to a recipe."""
recipe = get_recipe_detail(recipe_id, user=request.auth)
recipe = get_instance_detail(recipe_id, Recipe, request.auth)
recipe.image.save(img.name, img)
return {'success': True}


@recipe_router.delete('/{recipe_id}/image', response={204: None})
def delete_image(request, recipe_id: int):
"""Delete a recipe image."""
recipe = get_recipe_detail(recipe_id, user=request.auth)
recipe = get_instance_detail(recipe_id, Recipe, request.auth)
recipe.image.delete()
return 204, None

0 comments on commit 71c0d24

Please sign in to comment.