v2
This commit is contained in:
63
api/views.py
63
api/views.py
@@ -1,8 +1,10 @@
|
||||
from datetime import date
|
||||
|
||||
from rest_framework import status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from api.models import Aspect, Hero, Item
|
||||
from api.models import Aspect, BuildOfDay, Hero, Item
|
||||
from api.serializers import (
|
||||
HeroSerializer,
|
||||
ItemSerializer,
|
||||
@@ -101,3 +103,62 @@ class RandomizeBuildView(APIView):
|
||||
else:
|
||||
messages.append(f"{field}: {error}")
|
||||
return messages[0] if messages else "Invalid request data."
|
||||
|
||||
|
||||
class BuildOfDayView(APIView):
|
||||
"""
|
||||
GET: Return the build of the day. Generates one if it doesn't exist for today.
|
||||
"""
|
||||
|
||||
ITEMS_COUNT = 6
|
||||
|
||||
def get(self, request):
|
||||
today = date.today()
|
||||
|
||||
build = BuildOfDay.objects.filter(date=today).first()
|
||||
if not build:
|
||||
build = self._generate_build_of_day(today)
|
||||
if build is None:
|
||||
return Response(
|
||||
{"message": "Unable to generate build. Load data first."},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
response_data = {
|
||||
"date": build.date.isoformat(),
|
||||
"hero": HeroSerializer(build.hero).data,
|
||||
"items": ItemSerializer(build.items.all(), many=True).data,
|
||||
"skillBuild": build.skill_build,
|
||||
}
|
||||
|
||||
if build.aspect:
|
||||
response_data["aspect"] = build.aspect
|
||||
|
||||
return Response(response_data, status=status.HTTP_200_OK)
|
||||
|
||||
def _generate_build_of_day(self, today: date) -> BuildOfDay | None:
|
||||
"""Generate and save a new build of the day."""
|
||||
hero_count = Hero.objects.count()
|
||||
item_count = Item.objects.count()
|
||||
|
||||
if hero_count == 0 or item_count < self.ITEMS_COUNT:
|
||||
return None
|
||||
|
||||
hero_obj = Hero.objects.order_by("?").first()
|
||||
item_objs = list(Item.objects.order_by("?")[: self.ITEMS_COUNT])
|
||||
|
||||
aspect_name = None
|
||||
hero_aspects = Aspect.objects.filter(hero=hero_obj)
|
||||
if hero_aspects.exists():
|
||||
aspect_obj = hero_aspects.order_by("?").first()
|
||||
aspect_name = aspect_obj.name
|
||||
|
||||
build = BuildOfDay.objects.create(
|
||||
date=today,
|
||||
hero=hero_obj,
|
||||
skill_build=generate_skill_build(),
|
||||
aspect=aspect_name,
|
||||
)
|
||||
build.items.set(item_objs)
|
||||
|
||||
return build
|
||||
|
||||
Reference in New Issue
Block a user