Skip to content

Commit

Permalink
Refs #16 - When subscribing, respond to the client before sending the…
Browse files Browse the repository at this point in the history
… history
  • Loading branch information
johan-fvh committed Aug 21, 2020
1 parent 3652f56 commit a8540d1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
8 changes: 5 additions & 3 deletions backend/core/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,16 @@ class Meta:
fields = ('service', 'attributes', 'include_history')

def create(self, validated_data):
include_history = validated_data.pop('include_history', False)
self.include_history = validated_data.pop('include_history', False)
with transaction.atomic():
subscription = super().create(dict(user=self.context['request'].user, **validated_data))
subscription.create_in_service()
if include_history:
subscription.submit_history()
return subscription

def submit_history(self):
if self.include_history and self.instance:
self.instance.submit_history()


class SubscriptionSerializer(serializers.HyperlinkedModelSerializer):
service = ServiceSerializer()
Expand Down
21 changes: 20 additions & 1 deletion backend/core/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ class SensorAttributeViewSet(viewsets.ModelViewSet):
serializer_class = serializers.SensorAttributeSerializer


class AftereffectResponse(Response):
def __init__(self, *args, **kwargs):
self.aftereffect = kwargs.pop('aftereffect', None)
return super().__init__(*args, **kwargs)

def close(self):
super().close()
if self.aftereffect:
self.aftereffect()


class SubscriptionViewSet(
viewsets.mixins.ListModelMixin,
viewsets.mixins.CreateModelMixin,
Expand Down Expand Up @@ -100,11 +111,19 @@ def destroy(self, request, *args, **kwargs):
return Response(status=status.HTTP_204_NO_CONTENT)

def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)

try:
return super().create(request, *args, **kwargs)
self.perform_create(serializer)
except HTTPError:
return Response('Could not register subscription with service.', status=502)

headers = self.get_success_headers(serializer.data)
return AftereffectResponse(
serializer.data, status=status.HTTP_201_CREATED, headers=headers,
aftereffect=lambda: serializer.submit_history())


@api_view(['POST'])
@permission_classes([permissions.AllowAny])
Expand Down

0 comments on commit a8540d1

Please sign in to comment.