Skip to content

Commit

Permalink
Merge: drf-spectacluar 스키마 추가, 메시지 정렬 오류 수정, 테스트코드 수정
Browse files Browse the repository at this point in the history
[Inspection] drf-spectacluar 스키마 추가, 메시지 정렬 오류 수정, 테스트코드 수정
  • Loading branch information
yyysolhhh authored May 30, 2024
2 parents 3ed3b89 + 96598ed commit 232b84c
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 16 deletions.
2 changes: 1 addition & 1 deletion apps/chat/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class Meta:
class EnterChatroomSerializer(serializers.ModelSerializer[Chatroom]):
product_image = serializers.SerializerMethodField() # 상품 이미지
product_name = serializers.CharField(source="product.name", read_only=True)
product_rental_fee = serializers.CharField(source="product.rental_fee", read_only=True)
product_rental_fee = serializers.IntegerField(source="product.rental_fee", read_only=True)
product_condition = serializers.CharField(source="product.condition", read_only=True)

class Meta:
Expand Down
4 changes: 2 additions & 2 deletions apps/chat/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,8 @@ def test_채팅메시지가_db_redis에_분산되어_있는경우(self) -> None:
else:
data["nickname"] = self.user.nickname
self.redis_conn.lpush(key, json.dumps(data))
# self.assertEqual(self.redis_conn.llen(key), 10)
# self.assertEqual(Message.objects.count(), 50)
self.assertEqual(self.redis_conn.llen(key), 10)
self.assertEqual(Message.objects.count(), 50)

url = reverse("chat-detail", kwargs={"chatroom_id": self.chatroom.id})
response = self.client.get(url, headers={"Authorization": f"Bearer {self.token}"})
Expand Down
6 changes: 2 additions & 4 deletions apps/chat/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,13 +176,11 @@ def get_chatroom_message(chatroom_id: int) -> Any:
# 디비에 저장된 메시지가 30-stored_message_num 보다 많으면 슬라이싱해서 필요한 만큼의 데이터를 가져옴
if len(db_messages) >= 30 - stored_message_num:
serialized_messages = MessageSerializer(db_messages[: 30 - stored_message_num], many=True).data
serialized_message_list = [serialized_messages]
return messages + serialized_message_list
return messages + list(serialized_messages)

# 디비에 저장된 메시지가 30-stored_message_num 보다 적으면 db에 저장된 채팅방의 모든 메시지를 가져옴
serialized_messages = MessageSerializer(db_messages, many=True).data
serialized_message_list = [serialized_messages]
return messages + serialized_message_list
return messages + list(serialized_messages)

# 레디스에 해당 채팅방 그룹 네임으로 지정된 키값이 없으면 데이터베이스에서 채팅 메시지를 가져옴
db_messages = Message.objects.filter(chatroom_id=chatroom_id)
Expand Down
33 changes: 27 additions & 6 deletions apps/chat/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from django.db.models import Q
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from drf_spectacular.utils import extend_schema
from drf_spectacular.utils import extend_schema, inline_serializer
from rest_framework import serializers as serializer
from rest_framework import status
from rest_framework.request import Request
from rest_framework.response import Response
Expand All @@ -15,6 +16,7 @@
check_entered_chatroom,
delete_chatroom,
)
from apps.user.api_schema import UserInfoSerializer


def render_chat(request: HttpRequest) -> HttpResponse:
Expand All @@ -23,8 +25,18 @@ def render_chat(request: HttpRequest) -> HttpResponse:

class ChatRoomView(APIView):
@extend_schema(
request=serializers.ChatroomListSerializer,
responses=serializers.ChatroomListSerializer,
responses=inline_serializer(
name="ChatRoomSerializer",
fields={
"id": serializer.IntegerField(),
"product": serializer.UUIDField(),
"product_image": serializer.URLField(),
"last_message": serializer.CharField(),
"unread_chat_count": serializer.IntegerField(),
"user_info": UserInfoSerializer(),
},
many=True,
),
description="유저가 참여한 채팅방 리스트를 내려주는 get메서드",
)
def get(self, request: Request) -> Response:
Expand Down Expand Up @@ -58,10 +70,19 @@ def post(self, request: Request) -> Response:

class ChatDetailView(APIView):
@extend_schema(
responses=serializers.EnterChatroomSerializer,
responses=inline_serializer(
name="inline_serializer",
fields={
"product_image": serializer.CharField(),
"product_name": serializer.CharField(),
"product_rental_fee": serializer.CharField(),
"product_condition": serializer.CharField(),
"messages": serializers.MessageSerializer(many=True),
},
),
description="""
채팅방에 입장시 채팅방의 메시지를 내려주고, 상품에 대한 정보를 내려줌
""",
채팅방에 입장시 채팅방의 메시지를 내려주고, 상품에 대한 정보를 내려줌
""",
)
def get(self, request: Request, chatroom_id: int) -> Response:
try:
Expand Down
1 change: 0 additions & 1 deletion apps/product/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,5 @@ class RentalHistoryUpdateView(UpdateAPIView[RentalHistory]):
permission_classes = [permissions.IsAuthenticated]

def get_queryset(self) -> QuerySet[RentalHistory]:
print(self.request.data)
queryset = RentalHistory.objects.all()
return queryset
5 changes: 5 additions & 0 deletions apps/user/api_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,8 @@ class SignupRequestSchema(serializers.Serializer[Account]):
class SignupResponseSchema(serializers.Serializer[Account]):
access = serializers.CharField()
refresh = serializers.CharField()


class UserInfoSerializer(serializers.Serializer[Account]):
nickname = serializers.CharField()
profile_img = serializers.ImageField()
17 changes: 15 additions & 2 deletions apps/user/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
from django.core.cache import cache
from django.core.files.base import ContentFile
from django.utils import timezone
from drf_spectacular.utils import extend_schema
from rest_framework import permissions, status
from drf_spectacular.utils import extend_schema, inline_serializer
from rest_framework import permissions, serializers, status
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
Expand Down Expand Up @@ -156,6 +156,19 @@ class OAuthLoginView(APIView):
def get_provider_info(self) -> dict[str, Any]:
raise NotImplementedError

@extend_schema(
request=inline_serializer(name="CodeSeralizer", fields={"code": serializers.CharField()}),
responses=inline_serializer(
name="SocialLoginSeralizer",
fields={
"access": serializers.CharField(),
"refresh": serializers.CharField(),
"email": serializers.CharField(),
"nickname": serializers.CharField(),
"profile_image": serializers.ImageField(),
},
),
)
def post(self, request: Request, *args: Any, **kwargs: Any) -> Response:
code = request.data.get("code")
if not code:
Expand Down

0 comments on commit 232b84c

Please sign in to comment.