Skip to content

Commit

Permalink
Merge pull request #42 from dd-jiyun/jiyun
Browse files Browse the repository at this point in the history
fix: View Count
  • Loading branch information
dd-jiyun authored Mar 4, 2024
2 parents 5e31de3 + 5b4ea7b commit 9727f70
Showing 1 changed file with 41 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -146,33 +146,57 @@ private void validateAuthorIsLoggedInUser(Long id, User user) {
}
}

// μΏ ν‚€κ°€ μžˆλŠ”μ§€ 확인
private boolean containsViewCookie(Cookie[] cookies) {
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("viewCookie")) {
return true;
}
}
}
return false;
}

// 쑰회수 증가
private void validViewCount(Question question, HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
boolean isCookie = false;
if (cookies != null) {
for (Cookie value : cookies) {
if (value.getName().equals("viewCookie")) {
cookie = value;
boolean isCookie = containsViewCookie(cookies);

if (!isCookie) {
// μΏ ν‚€κ°€ μ—†λŠ” 경우
question.addViewCount();
Cookie newCookie = createViewCookie(question.getId(), calculateMaxAge());
response.addCookie(newCookie);
} else {
// μΏ ν‚€κ°€ μžˆλŠ” 경우
for (Cookie cookie : cookies) {
if (cookie.getName().equals("viewCookie")) {
if (!cookie.getValue().contains("[" + question.getId() + "]")) {
// λ°°μ—΄ μ•ˆμ— ν•΄λ‹Ή 아이디가 μ—†λŠ” 경우
question.addViewCount();
cookie.setValue(cookie.getValue() + "[" + question.getId() + "]");
response.addCookie(cookie);
}
isCookie = true;
break;
}
}
System.out.println("isCookie = " + isCookie);
if (!isCookie) {
question.addViewCount();
cookie = new Cookie("viewCookie", "[" + question.getId() + "]");
}
long todayEndSecond = LocalDate.now().atTime(LocalTime.MAX).toEpochSecond(ZoneOffset.UTC);
long currentSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
cookie.setPath("/");
cookie.setMaxAge((int) (todayEndSecond - currentSecond));
response.addCookie(cookie);
}
}

// μΏ ν‚€ 생성
private Cookie createViewCookie(long questionId, long maxAge) {
Cookie cookie = new Cookie("viewCookie", "[" + questionId + "]");
cookie.setPath("/");
cookie.setMaxAge((int) maxAge);
return cookie;
}

// ν•˜λ£¨μ˜ λκΉŒμ§€ 남은 μ‹œκ°„ 계산
private long calculateMaxAge() {
long todayEndSecond = LocalDate.now().atTime(LocalTime.MAX).toEpochSecond(ZoneOffset.UTC);
long currentSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
return todayEndSecond - currentSecond;
}

}

0 comments on commit 9727f70

Please sign in to comment.