diff --git a/api/schemas/subscriptions.py b/api/schemas/subscriptions.py index bf24ae1..b0cc16f 100644 --- a/api/schemas/subscriptions.py +++ b/api/schemas/subscriptions.py @@ -5,3 +5,9 @@ class SubscriptionIn(BaseModel): """Used to update a user's subscription to mark what entity IDs they've seen.""" last_seen_entity_id: int + + +class SubscriptionOut(BaseModel): + """Returned when a subscription is created""" + + last_seen_entity_id: int diff --git a/api/views/subscriptions.py b/api/views/subscriptions.py index 8942279..6f64874 100644 --- a/api/views/subscriptions.py +++ b/api/views/subscriptions.py @@ -5,14 +5,14 @@ from api.exceptions import APIException, NotFoundException from api.models import Card, Comment, Deck, Subscription, User from api.schemas import DetailResponse -from api.schemas.subscriptions import SubscriptionIn +from api.schemas.subscriptions import SubscriptionIn, SubscriptionOut router = APIRouter() @router.post( "/subscription/{entity_id}", - response_model=DetailResponse, + response_model=SubscriptionOut, status_code=status.HTTP_201_CREATED, responses={ 400: { @@ -50,7 +50,6 @@ def create_subscription( # Cards don't have this attribute, so we can safely ignore it pass - success_response = {"detail": "You have subscribed to this content."} # Check if they already have a subscription subscription = ( session.query(Subscription) @@ -61,19 +60,19 @@ def create_subscription( .first() ) if subscription: - return success_response + return {"last_seen_entity_id": subscription.last_seen_entity_id} # Look up the most recently seen entity ID (assumes that they subscribed from the detail page, since it's silly to # force them to immediately update the last seen ID after subscribing). - last_seen_entity_id = ( + last_seen = ( session.query(Comment.entity_id) .filter(Comment.source_entity_id == entity_id) .order_by(Comment.entity_id.desc()) - .scalar() + .first() ) - if not last_seen_entity_id and is_deck: + if not last_seen and is_deck: # If we don't have any comments on this deck, grab the latest entity ID for the most recent published snapshot - last_seen_entity_id = ( + last_seen = ( session.query(Deck.entity_id) .filter( Deck.source_id == source.id, @@ -82,7 +81,7 @@ def create_subscription( Deck.is_public == True, ) .order_by(Deck.entity_id.desc()) - .scalar() + .first() ) # Create a new subscription @@ -90,11 +89,11 @@ def create_subscription( Subscription( user_id=current_user.id, source_entity_id=entity_id, - last_seen_entity_id=last_seen_entity_id, + last_seen_entity_id=last_seen.entity_id, ) ) session.commit() - return success_response + return {"last_seen_entity_id": last_seen.entity_id} @router.delete( @@ -123,6 +122,7 @@ def delete_subscription( Subscription.user_id == current_user.id, Subscription.source_entity_id == entity_id, ).delete() + session.commit() return Response(status_code=status.HTTP_204_NO_CONTENT)