2023-02-08

강혜성·2023년 2월 8일
0

ZZALU 프로젝트

목록 보기
8/11

채팅방 즐겨찾기 구현

  • 즐겨 찾기 구현은 N:M 관계로 (Member : ChatRoom)
  • 좋아요을 눌렀을 때, 해당 채팅방의 like count를 1증가시켜준다.
  • 해당 좋아요를 누른 사람 목록을 채팅방의 like members에 추가한다.
 	@PostMapping("/like")
    @ResponseBody
    public boolean updateLikeCount(@RequestHeader(value = "Authorization")String bearerToken, @RequestBody Map<String, String> map){

        // AccessToken 검증 필요
        String token = bearerToken.substring(7);
        Member requestMember = jwtTokenProvider.getMember(token);

        String roomId = map.get("roomId");
        System.out.println("RoomId : " + roomId);
        Optional<ChatRoom> optionalChatRoom = chatRoomService.findByRoomId(roomId);
        if(optionalChatRoom.isPresent()) {
            ChatRoom chatRoom = optionalChatRoom.get();
            System.out.println("chatRoom.getLikeMembers() : " + chatRoom.getLikeMembers());
            if(!chatRoom.getLikeMembers().contains(requestMember)) {
                requestMember.addLikeChatRoom(chatRoom);
                chatRoom.setLikeCount(chatRoom.getLikeCount() + 1);
                chatRoomService.save(chatRoom);
                return true;
            } else {
                System.out.println("이미 클릭한 사용자 입니다. Error Exception 필요");
                return false;
            }
        }
        else {
            System.out.println("Can't find chatRoom Error");
            return false;
        }
    }
  • 채팅방 순환 참조 DTO를 생성해서 해결
package com.samsamoo.zzalu.chat.dto;

import com.samsamoo.zzalu.chat.entity.ChatMessage;
import com.samsamoo.zzalu.chat.entity.ChatRoom;
import com.samsamoo.zzalu.member.entity.Member;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
public class ChatRoomListDto {
    private String roomId;
    private String roomName;
    private String userNmae;
    private Long memberId;
    private Long likeCount;

    private List<ChatMessage> chatMessages;
    private List<Long> likeMemberId;
    private String imagePath;
    private String description;
    private String tags;
    private LocalDateTime enrollDate;
    private LocalDateTime lastActivation;

    public ChatRoomListDto(ChatRoom chatRoom) {
        roomId = chatRoom.getRoomId();
        roomName = chatRoom.getRoomName();
        userNmae = chatRoom.getUserNmae();
        memberId = chatRoom.getMemberId();
        likeCount = chatRoom.getLikeCount();
        chatMessages = chatRoom.getChatMessages();
        likeMemberId = new ArrayList<>();
        for(Member member : chatRoom.getLikeMembers()) {
            likeMemberId.add(member.getId());
        }
        imagePath = chatRoom.getImagePath();
        description = chatRoom.getDescription();
        tags = chatRoom.getTags();
        enrollDate = chatRoom.getEnrollDate();
        lastActivation = chatRoom.getLastActivation();
    }
}

짤 사용 통계 JPA 설계

  • Member와 해당 사용자가 사용한 짤의 태그를 저장할 MemberTagStatistics를 1 : N 관계로 지정하면 Member 전체의 정보를 받아오므로 memberId 값만 주어 조회해서 찾는다.
[ MemberTagStatistics Entity ]
package com.samsamoo.zzalu.statistics.entity;

import com.samsamoo.zzalu.member.entity.Member;
import lombok.*;

import javax.persistence.*;

@Entity
@Setter
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class MemberTagStatistics {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JoinColumn(name = "member_id")
    private Long memberId;

    @Column(name = "tag")
    private String tag;

    @Column(name = "COUNT")
    @Builder.Default
    private Long count = 0L;
}
  • Gif도 마찬가지로 gif id만 가져온다. 1:1 관계이므로 unique = true 옵션을 설정한다.
[GifStatisticsEntity]

package com.samsamoo.zzalu.statistics.entity;

import lombok.*;

import javax.persistence.*;

@Entity
@Setter
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GifStatistics {
    @Id
    @Column(name = "GIFS_STATISTICS_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "GIF_ID", unique = true)
    private Long gifId;

    @Column(name = "USE_COUNT")
    @Builder.Default
    private Long useCount = 0L;

    @Column(name = "DOWNLOAD_COUNT")
    @Builder.Default
    private Long downloadCount = 0L;
}
  • Statistics Contoller를 생성한다.
  • download, use는 대부분 같은 기능을 하지만 추후에 다른 기능이 필요할 수 있기 때문에 분리한다.
[Statistics Contoller]

package com.samsamoo.zzalu.statistics.controller;

import com.samsamoo.zzalu.auth.sevice.JwtTokenProvider;
import com.samsamoo.zzalu.gifs.entity.Gifs;
import com.samsamoo.zzalu.gifs.service.GifsService;
import com.samsamoo.zzalu.member.entity.Member;
import com.samsamoo.zzalu.statistics.entity.GifStatistics;
import com.samsamoo.zzalu.statistics.entity.MemberTagStatistics;
import com.samsamoo.zzalu.statistics.repository.MemberTagStatisticsRepository;
import com.samsamoo.zzalu.statistics.service.GifStatisticsService;
import com.samsamoo.zzalu.statistics.service.MemberTagStatisticsService;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RequiredArgsConstructor
@RestController
@RequestMapping("/statistics")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class StatisticsController {

    private final GifsService gifsService;
    private final GifStatisticsService gifStatisticsService;
    private final MemberTagStatisticsService memberTagStatisticsService;
    private final JwtTokenProvider jwtTokenProvider;
    private final MemberTagStatisticsRepository memberTagStatisticsRepository;

    @GetMapping("/use")
    @ResponseBody
    public boolean updateTagUseCount(@RequestHeader(value = "Authorization")String bearerToken, @RequestParam("gifId") Long gifId){

        String token = bearerToken.substring(7);
        Member requestMember = jwtTokenProvider.getMember(token);

        if(gifsService.findById(gifId).isPresent()){
            Gifs gif = gifsService.findById(gifId).get();
            String[] tags = gif.getTags().split(",");

            for(int index = 0; index < tags.length; ++index) {
                Optional<MemberTagStatistics> optionalMemberTagStatistics = memberTagStatisticsService.findByTagAndMemberId(tags[index], requestMember.getId());

                if(optionalMemberTagStatistics.isPresent()) {
                    MemberTagStatistics memberTagStatistics = optionalMemberTagStatistics.get();
                    memberTagStatistics.setCount(memberTagStatistics.getCount() + 1);
                    memberTagStatisticsService.save(memberTagStatistics);
                } else {
                    MemberTagStatistics newMemberTagStatistics = new MemberTagStatistics();
                    newMemberTagStatistics.setMemberId(requestMember.getId());
                    newMemberTagStatistics.setTag(tags[index]);
                    newMemberTagStatistics.setCount(1L);
                    memberTagStatisticsService.save(newMemberTagStatistics);
                }
            }

            Optional<GifStatistics> optionalGifStatistics = gifStatisticsService.findByGifId(gif.getId());
            GifStatistics gifStatistics;
            if(optionalGifStatistics.isPresent()) {
                gifStatistics = optionalGifStatistics.get();
                gifStatistics.setUseCount(gifStatistics.getUseCount() + 1);
            } else {
                gifStatistics = new GifStatistics();
                gifStatistics.setUseCount(1L);
                gifStatistics.setGifId(gif.getId());
            }
            gifStatisticsService.save(gifStatistics);

            return true;
        } else {
            System.out.println("gif Error");
            return false;
        }
    }

    @GetMapping("/download")
    @ResponseBody
    public boolean updateTagDownloadCount(@RequestHeader(value = "Authorization")String bearerToken, @RequestParam("gifId") Long gifId){

        String token = bearerToken.substring(7);
        Member requestMember = jwtTokenProvider.getMember(token);

        if(gifsService.findById(gifId).isPresent()){
            Gifs gif = gifsService.findById(gifId).get();
            String[] tags = gif.getTags().split(",");

            for(int index = 0; index < tags.length; ++index) {
                Optional<MemberTagStatistics> optionalMemberTagStatistics = memberTagStatisticsService.findByTagAndMemberId(tags[index], requestMember.getId());

                if(optionalMemberTagStatistics.isPresent()) {
                    MemberTagStatistics memberTagStatistics = optionalMemberTagStatistics.get();
                    memberTagStatistics.setCount(memberTagStatistics.getCount() + 1);
                    memberTagStatisticsService.save(memberTagStatistics);
                } else {
                    MemberTagStatistics newMemberTagStatistics = new MemberTagStatistics();
                    newMemberTagStatistics.setMemberId(requestMember.getId());
                    newMemberTagStatistics.setTag(tags[index]);
                    newMemberTagStatistics.setCount(1L);
                    memberTagStatisticsService.save(newMemberTagStatistics);
                }
            }

            Optional<GifStatistics> optionalGifStatistics = gifStatisticsService.findByGifId(gif.getId());
            GifStatistics gifStatistics;
            if(optionalGifStatistics.isPresent()) {
                gifStatistics = optionalGifStatistics.get();
                gifStatistics.setDownloadCount(gifStatistics.getDownloadCount() + 1);
            } else {
                gifStatistics = new GifStatistics();
                gifStatistics.setDownloadCount(1L);
                gifStatistics.setGifId(gif.getId());
            }
            gifStatisticsService.save(gifStatistics);

            return true;
        } else {
            System.out.println("gif Error");
            return false;
        }
    }

    // AccessToken이 아니라 MemberId로 받도록 수정
    @GetMapping("/member")
    @ResponseBody
    public List<MemberTagStatistics> findAllByMemberId(@RequestParam("memberId") Long memberId){
        return memberTagStatisticsService.findAllByMemberId(memberId);
    }

    @GetMapping("/gif")
    @ResponseBody
    public GifStatistics findByGifId(@RequestParam("gifId") Long gifId){
        System.out.println(gifId);
        Optional<GifStatistics> optionalGifStatistics = gifStatisticsService.findByGifId(gifId);
        return optionalGifStatistics.orElse(null);
    }


}

0개의 댓글