Way simpler implementation of the new endpoints

Signed-off-by: Paul Konstantin Gerke <paulkgerke@craftware.info>
This commit is contained in:
Paul Konstantin Gerke 2022-01-12 00:25:22 +01:00 committed by Christopher Charbonneau Wells
parent 53d4759add
commit c1a0abd1f7
1 changed files with 7 additions and 29 deletions

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from rest_framework import viewsets, status from rest_framework import viewsets
from rest_framework.decorators import action from rest_framework.decorators import action
from rest_framework.response import Response from rest_framework.response import Response
@ -51,39 +51,17 @@ class TimerViewSet(viewsets.ModelViewSet):
serializer_class = serializers.TimerSerializer serializer_class = serializers.TimerSerializer
filterset_class = filters.TimerFilter filterset_class = filters.TimerFilter
def __timer_operation(self, pk, func):
try:
timer = models.Timer.objects.get(pk=pk)
return func(timer)
except models.Timer.DoesNotExist:
return Response(
{"detail": "timer does not exist"},
status=status.HTTP_404_NOT_FOUND
)
@action(detail=True, methods=['patch']) @action(detail=True, methods=['patch'])
def stop(self, request, pk=None): def stop(self, request, pk=None):
def do_stop(timer): timer = self.get_object()
if not timer.active: timer.stop()
return Response( return Response(self.serializer_class(timer).data)
{"detail": "timer already stopped"},
status=status.HTTP_412_PRECONDITION_FAILED
)
timer.stop()
return Response({"detail": "timer stopped"})
return self.__timer_operation(pk, do_stop)
@action(detail=True, methods=['patch']) @action(detail=True, methods=['patch'])
def restart(self, request, pk=None): def restart(self, request, pk=None):
def do_restart(timer): timer = self.get_object()
if timer.active: timer.restart()
return Response( return Response(self.serializer_class(timer).data)
{"detail": "timer already active"},
status=status.HTTP_412_PRECONDITION_FAILED
)
timer.restart()
return Response({"detail": "timer restarted"})
return self.__timer_operation(pk, do_restart)
class TummyTimeViewSet(TimerFieldSupportMixin, viewsets.ModelViewSet): class TummyTimeViewSet(TimerFieldSupportMixin, viewsets.ModelViewSet):