Skip to content

Commit

Permalink
이번주 인기 있는 기사 10개 조회하는 API로 리팩토링 (#65)
Browse files Browse the repository at this point in the history
* refactor : 이번주 인기 있는 기사 조회 API로 리팩토링

* refactor : 기사 10개만 들고 오기!

---------

Co-authored-by: stopmin <geemin0@naver.com>
  • Loading branch information
pykido and stopmin authored Jul 19, 2024
1 parent 26a5069 commit 45157f6
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 38 deletions.
24 changes: 12 additions & 12 deletions src/main/java/gyeongdan/article/controller/ArticleController.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class ArticleController {
// 단, 유저가 보면 조회기록 저장하고, 유저가 아닌 경우 조회수만 증가시키기.
@GetMapping("/detail")
public ResponseEntity<?> getArticle(@RequestParam Long id,
@RequestHeader @Nullable String accessToken) { // id : 기사id, access token : 유저의 접근 권한
@RequestHeader @Nullable String accessToken) { // id : 기사id, access token : 유저의 접근 권한
Optional<Long> userId = Optional.empty();
if (accessToken != null && !accessToken.isEmpty()) {
userId = jwtUtil.getUserId(jwtUtil.resolveToken(accessToken));
Expand Down Expand Up @@ -63,21 +63,21 @@ public ResponseEntity<?> getRecentViewedArticles(@RequestHeader @Nullable String
List<Article> recentViewedArticles = articleService.getRecentViewedArticles(userId.orElse(null));

List<ArticleAllResponse> finalResponse = recentViewedArticles.stream()
.map(article -> new ArticleAllResponse(
article.getId(),
article.getSimpleTitle(),
article.getSimpleContent(),
article.getViewCount(),
article.getCategory(),
Optional.ofNullable(article.getImageUrl()),
article.getPublishedAt()
))
.collect(Collectors.toList());
.map(article -> new ArticleAllResponse(
article.getId(),
article.getSimpleTitle(),
article.getSimpleContent(),
article.getViewCount(),
article.getCategory(),
Optional.ofNullable(article.getImageUrl()),
article.getPublishedAt()
))
.collect(Collectors.toList());

return ResponseEntity.ok(new CommonResponse<>(finalResponse, "가장 최근에 조회한 게시글 3개 조회 성공", true));
}

// 오늘 가장 인기 있는 기사 5개 조회 (조회수 기준)
// 이번주 가장 인기 있는 기사 10개 조회 (조회수 기준)
@GetMapping("/popular")
public ResponseEntity<?> getPopularArticles() {
List<PopularArticleResponse> popularArticles = articleService.getPopularArticles();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
package gyeongdan.article.repository;

import gyeongdan.article.domain.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

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

@Repository
public interface ArticleJpaRepository extends JpaRepository<Article, Long> {

List<Article> findTop10ByPublishedAtBetweenOrderByViewCountDesc(LocalDateTime startOfWeek, LocalDateTime endOfDay);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,4 @@

public interface ArticleViewHistoryJpaRepository extends JpaRepository<ArticleViewHistory, Long> {
List<ArticleViewHistory> findTop100ByUserIdOrderByViewedAtDesc(Long userId);

@Query("SELECT a.article FROM ArticleViewHistory a WHERE a.viewedAt >= :startOfDay AND a.viewedAt < :endOfDay GROUP BY a.article ORDER BY SUM(a.article.viewCount) DESC")
List<Article> findTopArticlesByViewedAtBetween(@Param("startOfDay") LocalDateTime startOfDay, @Param("endOfDay") LocalDateTime endOfDay);
}
49 changes: 27 additions & 22 deletions src/main/java/gyeongdan/article/service/ArticleService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
import gyeongdan.article.dto.ArticleAllResponse;
import gyeongdan.article.dto.ArticleUpdateRequest;
import gyeongdan.article.dto.PopularArticleResponse;
import gyeongdan.article.repository.ArticleJpaRepository;
import gyeongdan.article.repository.ArticleRepository;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
Expand All @@ -16,6 +18,7 @@
import gyeongdan.article.repository.ArticleViewHistoryJpaRepository;
import gyeongdan.user.service.UserManageService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
Expand All @@ -25,6 +28,7 @@ public class ArticleService {
private final ArticleRepository articleRepository;
private final ArticleViewHistoryJpaRepository articleViewHistoryJpaRepository;
private final UserManageService userManageService;
private final ArticleJpaRepository articleJpaRepository;

public Article getValidArticleById(Long id, Optional<Long> userId) {
Article article = articleRepository.findById(id);
Expand Down Expand Up @@ -68,17 +72,17 @@ public Long updateArticle(ArticleUpdateRequest articleUpdateRequest) {
public List<ArticleAllResponse> getValidArticles() {
List<Article> articles = articleRepository.findAll();
return articles.stream()
.filter(Article::isValid)
.map(article -> new ArticleAllResponse(
article.getId(),
article.getSimpleTitle(),
article.getSimpleContent(),
article.getViewCount(),
article.getCategory(),
Optional.ofNullable(article.getImageUrl()),
article.getPublishedAt()
))
.collect(Collectors.toList());
.filter(Article::isValid)
.map(article -> new ArticleAllResponse(
article.getId(),
article.getSimpleTitle(),
article.getSimpleContent(),
article.getViewCount(),
article.getCategory(),
Optional.ofNullable(article.getImageUrl()),
article.getPublishedAt()
))
.collect(Collectors.toList());
}

// 조회수 증가 메서드
Expand All @@ -97,24 +101,25 @@ public List<Article> getRecentViewedArticles(Long userId) {
userManageService.checkUserExist(userId);

List<ArticleViewHistory> recentViewedHistories = articleViewHistoryJpaRepository.findTop100ByUserIdOrderByViewedAtDesc(
userId);
userId);
return recentViewedHistories.stream()
.map(ArticleViewHistory::getArticle)
.distinct()
.limit(3)
.collect(Collectors.toList());
.map(ArticleViewHistory::getArticle)
.distinct()
.limit(3)
.collect(Collectors.toList());
}

// 오늘 가장 인기 있는 기사 5개 가져오는 메서드 (조회수 기준)
// 이번 주 가장 인기 있는 기사 5개 가져오는 메서드 (조회수 기준)
public List<PopularArticleResponse> getPopularArticles() {
// 오늘을 기준으로 이번 주의 시작과 끝을 구함 (월요일부터 일요일까지)
LocalDate today = LocalDate.now();
LocalDateTime startOfDay = today.atStartOfDay();
LocalDateTime endOfDay = today.plusDays(1).atStartOfDay();
LocalDateTime mondayDateTime = today.with(DayOfWeek.MONDAY).atStartOfDay();
LocalDateTime sundayDateTime = today.with(DayOfWeek.SUNDAY).plusDays(1).atStartOfDay();

List<Article> articles = articleViewHistoryJpaRepository.findTopArticlesByViewedAtBetween(startOfDay, endOfDay);
List<Article> articles = articleJpaRepository.findTop10ByPublishedAtBetweenOrderByViewCountDesc(mondayDateTime, sundayDateTime);

return articles.stream()
.map(article -> new PopularArticleResponse(article.getId(), article.getSimpleTitle(), article.getViewCount()))
.collect(Collectors.toList());
.map(article -> new PopularArticleResponse(article.getId(), article.getSimpleTitle(), article.getViewCount()))
.collect(Collectors.toList());
}
}
1 change: 0 additions & 1 deletion src/main/java/gyeongdan/user/domain/UserType.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package gyeongdan.user.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
Expand Down

0 comments on commit 45157f6

Please sign in to comment.