Django ⎮ 위시리스트 API

Chris-Yang·2021년 10월 24일
1

Django

목록 보기
4/7
post-thumbnail

> Flow

-POST 요청(위시리스트 등록 / 삭제 - 토클 개념 활용)
1. 해당하는 제품이 있는지 product db를 조회 / 예외처리를 합니다.
2. 유저id와 상품id를 FE에서 받아와서 Wishlist db를 조회합니다.
3. Wishlist db에 일치하는 조건이 없으면 해당 조건으로 wishlist row를 생성합니다.
4. 반대로 Wishlist table에 일치하는 조건이 있으면 해당 wishlist를 삭제합니다.

-GET 요청(위시리스트 가져오기)
1. 유저id를 통해 Wishlist db에서 내가 담은 상품을 조회합니다.
2. 조회한 결과를 통해 product table 등 관계된 table에 접근하여 배열에 각각 객체형태로 하나씩 저장합니다.




> Code

import json
from json.decoder import JSONDecodeError

from django.http import JsonResponse
from django.views import View

from products.models import Product, Wishlist
from users.utils  import login_decorator

class WishList(View):
    @login_decorator
    def post(self, request):
        try:
            user_id      = request.user.id
            # 제품 상세페이지와 마이페이지 두군데서 API를 쓰기 때문에 query parameter를 사용했습니다.
            wish_product = request.GET.get('product_id')

	    # 해당하는 제품이 있는지 product db를 조회 / 예외처리를 합니다.
            if not Product.objects.filter(id = wish_product).exists():
                return JsonResponse({'message:' : 'INVALID_PRODUCT_ID'}, status = 404)

	    # 유저id와 상품id를 통해 Wishlist db를 조회합니다.
            if not Wishlist.objects.filter(user_id = user_id, product_id = wish_product).exists():
                Wishlist.objects.create(user_id = user_id, product_id = wish_product)

                wish_count = Wishlist.objects.filter(product_id = wish_product).count()

                return JsonResponse({'message' : 'WISH_CREATE_SUCCESS', 'wish_count' : wish_count}, status = 201)

	    # 반대로 Wishlist table에 일치하는 조건이 있으면 해당 wishlist를 삭제합니다.
            Wishlist.objects.get(user_id = user_id, product_id = wish_product).delete()

            wish_count = Wishlist.objects.filter(product_id = wish_product).count()

            return JsonResponse({'message' : 'WISH_DELETE_SUCCESS', 'wish_count' : wish_count}, status = 200)
        
        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'}, status = 400)

        except JSONDecodeError:
            return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status = 400)

    @login_decorator
    def get(self, request):
        try:
            user_id = request.user

	    # 유저id를 통해 Wishlist db에서 내가 담은 상품을 조회합니다.
            wish_list = Wishlist.objects.filter(user_id=user_id)

	    # 조회한 결과를 통해 product table 등 관계된 table에 접근합니다.
            results = [{
                "brand" : wish.product.brand.name,
                "name"  : wish.product.name,
                "price" : wish.product.release_price,
                "image" : [
                    {
                        "thumbnail" : img.image_url
                    } for img in wish.product.productimage_set.all()[:1]]
                } for wish in wish_list]

            return JsonResponse({'results': results}, status=200)
        
        except JSONDecodeError:
            return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status = 400)

class WishFlag(View):
    @login_decorator
    def get(self, request):
        try:
            user_id      = request.user.id
            wish_product = request.GET.get('product_id')

            if not Product.objects.filter(id = wish_product):
                return JsonResponse({'message:' : 'INVALID_PRODUCT_ID'}, status = 404)

            wish_count = Wishlist.objects.filter(product_id = wish_product).count()

	    # 제품과 함께 자신의 좋아요 여부가 표시가 되기 때문에 상태를 체크해줍니다.
            check_my_wish = True

            if not Wishlist.objects.filter(product_id = wish_product, user_id = user_id):
                check_my_wish = False

            results = {
                'wish_count'    : wish_count,
                'check_my_wish' : check_my_wish,
            }

            return JsonResponse({'results' : results}, status = 200)
    
        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'}, status = 400)



> Divide & Conquer

▶︎ wishlist에 담을 제품 조회 / 토글

- WishList API

if not Wishlist.objects.filter(user_id = user_id, product_id = wish_product).exists():
    Wishlist.objects.create(user_id = user_id, product_id = wish_product)

    wish_count = Wishlist.objects.filter(product_id = wish_product).count()

    return JsonResponse({'message' : 'WISH_CREATE_SUCCESS', 'wish_count' : wish_count}, status = 201)

Wishlist.objects.get(user_id = user_id, product_id = wish_product).delete()

wish_count = Wishlist.objects.filter(product_id = wish_product).count()

return JsonResponse({'message' : 'WISH_DELETE_SUCCESS', 'wish_count' : wish_count}, status = 200)

해당하는 조건이 wishlist table에 존재하는지 확인합니다.

만약 존재하지 않는 경우 wishilst table에 유저id와 상품id를 담은 row를 생성해줍니다.

반대로 존재하는 경우 해당 row를 삭제하여 장바구니에서 삭제되도록 합니다.

만약 회원에게 추천상품을 제시하는 데이터가 필요한 경우라면 삭제가 아닌
boolean column을 이용해 True와 False를 토글해 주고 값이 False인 경우
해당 데이터를 제외하고 통신하던가 FE측에서 노출되지 않게 하여
유저가 어떤 상품에 관심이 있었는지 데이터를 축척하는 방법도 좋아보입니다.

또한 실수 등으로 인한 클릭에 대해서는 아마도 빠르게 취소할 것이므로
이 부분도 구분할 수 있는 로직을 생각할 필요가 있을 것 같습니다.
(예: 생성시간과 업데이트 시간차를 계산하여 10초 이하 시 row 삭제)


- WishFlag API

check_my_wish = True

if not Wishlist.objects.filter(product_id = wish_product, user_id = user_id):
    check_my_wish = False

페이지를 이동할때 해당 상품에 대해 관심상품으로 등록했는지에 대한 정보가
필요했기 때문에 상태를 체크하고 구분을 True, False로 FE에 전달하였습니다.

profile
sharing all the world

0개의 댓글