-
Notifications
You must be signed in to change notification settings - Fork 20
/
article_vote_view.py
75 lines (66 loc) · 3.01 KB
/
article_vote_view.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from http import HTTPStatus
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
from myapp.application.adapter.api.http.problem_response import problem_response
from myapp.application.adapter.api.http.serializer.successfully_voted_result_serializer import ( # noqa
SuccessfullyVotedResultSerializer
)
from myapp.application.adapter.api.http.serializer.vote_for_article_command_deserializer import ( # noqa
VoteForArticleCommandDeserializer
)
from myapp.application.domain.model.vote_for_article_result import (
AlreadyVotedResult,
InsufficientKarmaResult,
SuccessfullyVotedResult,
VoteForArticleResult
)
from myapp.application.port.api.command.vote_for_article_command import (
VoteForArticleCommand
)
from myapp.application.port.api.vote_for_article_use_case import (
VoteForArticleUseCase
)
from myapp.application.util.assert_never import assert_never
class ArticleVoteView(APIView):
# default `None` and # `type: ignore` for sake of .as_view()
# which requires passed attributes to be declared on the class level :(
vote_for_article_use_case: VoteForArticleUseCase = None # type: ignore
def __init__(self, vote_for_article_use_case: VoteForArticleUseCase):
self.vote_for_article_use_case = vote_for_article_use_case
super().__init__()
def post(self, request: Request) -> Response:
vote_for_article_command = self._read_command(request)
result = self.vote_for_article_use_case.vote_for_article(
vote_for_article_command
)
return self._build_response(result)
def _read_command(self, request: Request) -> VoteForArticleCommand:
serializer = VoteForArticleCommandDeserializer(data=request.data)
serializer.is_valid(raise_exception=True)
return serializer.create()
def _build_response(self, voting_result: VoteForArticleResult) -> Response:
response = None
match voting_result:
case SuccessfullyVotedResult():
response_data = SuccessfullyVotedResultSerializer(voting_result).data
response = Response(response_data, status=HTTPStatus.CREATED)
case InsufficientKarmaResult(user_id):
detail = f"User {user_id} does not have enough karma" \
" to vote for an article"
response = problem_response(
title="Cannot vote for an article",
detail=detail,
status=HTTPStatus.BAD_REQUEST
)
case AlreadyVotedResult(article_id, user_id):
detail = f"User \"{user_id}\" has already voted " \
f"for article \"{article_id}\""
response = problem_response(
title="Cannot vote for an article",
detail=detail,
status=HTTPStatus.CONFLICT
)
case _:
assert_never(voting_result)
return response