티스토리 뷰

구독기능 구현하기

구독 여부에 따른 버튼 표시와 구독 카운트를 추가할려고한다

프로필페이지만들때 만든 UserProfileDetail로 맴버를 추가해주자.

 

UserProfileDeatil.java

@Builder
@AllArgsConstructor // 전체생성자
@NoArgsConstructor // 빈생성자 
@Data
public class UserProfileDto {

	private boolean PageOwnerState;
	private User user;
	private boolean subscribeState;
	private int subscribeCount;
	private int imageCount;
}

구독여부와 구독갯수를 추가해주었다.

위와같이 1번이 2,3번을 구독하고 2번이 1,3번을 구독한 상태의 테이블을 설정하였다

1번이 2번페이지로 가게되면 구독취소버튼이 보여야하고

 

쿼리문은 어떻게 생겼을까?

구독하고있는 수

SELECT COUNT(*) FROM subscribe WHERE fromUserId = 1;

결과 2

 

구독여부 (로그인1번, 2번페이지를 볼때)

SELECT COUNT(*) FROM subscribe WHERE fromUserId = 1 AND toUserId =2;

결과 1

1이라는건 구독을했다는 뜻이고 0이라는건 구독을 안했다는 뜻이된다.

 

위 쿼리문을 이용하여 네이티브 쿼리를 작성해줘야한다.

 

SubscribeRepository.java 인터페이스

	@Query(value="SELECT COUNT(*) FROM subscribe WHERE fromUserId = :principalId AND toUserId =:pageUserId",nativeQuery = true)
	int mSubScribeState(int principalId, int pageUserId);
	
	@Query(value="SELECT COUNT(*) FROM subscribe WHERE fromUserId = :pageUserId",nativeQuery = true)
	int mSubscribeCount(int pageUserId);

두개의 네이티브 쿼리문 추가

 

UserService의 회원프로필 함수에 코드 추가

		int subscribeState =  subscribeRepository.mSubScribeState(principalld, pageUserId);
		int subscribeCount = subscribeRepository.mSubscribeCount(pageUserId);
		
		dto.setSubscribeCount(subscribeCount);
		dto.setSubscribeState(subscribeState == 1);

네이티브쿼리로 가져온 결과를 dto에 set해주고 반환해주면 구독수와 구독여부가 담겨 들어가게된다.

 

    <div class="name-group">
        <h2>${dto.user.name}</h2>

        <c:choose>
            <c:when test="${dto.pageOwnerState }">
                <button class="cta" onclick="location.href='/image/upload'">사진등록</button>
            </c:when>
            <c:otherwise>
                <c:choose>
                    <c:when test="${dto.subscribeState }">
                        <button class="cta blue" onclick="toggleSubscribe(${dto.user.id},this)">구독취소</button>
                    </c:when>
                    <c:otherwise>
                        <button class="cta" onclick="toggleSubscribe(${dto.user.id},this)">구독하기</button>
                    </c:otherwise>
                </c:choose>
            </c:otherwise>
        </c:choose>
        <button class="modi" onclick="popup('.modal-info')">
            <i class="fas fa-cog"></i>
        </button>
    </div>
            
 <script src="/js/profile.js"></script>

toggleSubscribe에 해당 페이지의 유저정보에 id를 넣어주고 그 id를 기반으로 스크립트를 작성해야한다

이제 버튼을 누르면 구독이되거나 구독이 취소 되도록 만들어보자

 

profile.js

function toggleSubscribe(toUserId,obj) {
	if ($(obj).text() === "구독취소") {
		
		$.ajax({
			type:"delete",
			url:"/api/subscribe/"+toUserId,
			dataType:"json"
		}).done(res=>{
			$(obj).text("구독하기");		
			$(obj).toggleClass("blue");
		}).fail(err=>{
			console.log("구독취소실패",err);
		});
		
	} else {
		$.ajax({
			type:"post",
			url:"/api/subscribe/"+toUserId,
			dataType:"json"
		}).done(res=>{
			$(obj).text("구독취소");		
			$(obj).toggleClass("blue");
		}).fail(err=>{
			console.log("구독실패",err);
		});
	}
}

해당 버튼 안의 text로 판별을 하고 요청에 따라 다른 기능이 실행되어 ajax가 발동되게된다.

이제 구독취소와 구독버튼을 누르면 정상적으로 작동할것이다 DB를 통해 한번더 확인하자

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
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
글 보관함