Add ranking endpoint and UI

This commit is contained in:
Tim
2025-07-09 20:48:58 +08:00
parent db58af31c9
commit befe0ff470
4 changed files with 88 additions and 11 deletions

View File

@@ -78,13 +78,20 @@ public class PostController {
}
if (hasTags) {
return postService.listPostsByTags(tids, page, pageSize)
.stream().map(this::toDto).collect(Collectors.toList());
.stream().map(this::toDto).collect(Collectors.toList());
}
return postService.listPostsByCategories(ids, page, pageSize)
.stream().map(this::toDto).collect(Collectors.toList());
}
@GetMapping("/ranking")
public List<PostDto> rankingPosts(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "pageSize", required = false) Integer pageSize) {
return postService.listPostsByViews(page, pageSize)
.stream().map(this::toDto).collect(Collectors.toList());
}
private PostDto toDto(Post post) {
PostDto dto = new PostDto();
dto.setId(post.getId());

View File

@@ -16,6 +16,8 @@ import org.springframework.data.repository.query.Param;
public interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findByStatus(PostStatus status);
List<Post> findByStatus(PostStatus status, Pageable pageable);
List<Post> findByStatusOrderByViewsDesc(PostStatus status);
List<Post> findByStatusOrderByViewsDesc(PostStatus status, Pageable pageable);
List<Post> findByAuthorAndStatusOrderByCreatedAtDesc(User author, PostStatus status, Pageable pageable);
List<Post> findByCategoryInAndStatus(List<Category> categories, PostStatus status);
List<Post> findByCategoryInAndStatus(List<Category> categories, PostStatus status, Pageable pageable);

View File

@@ -107,6 +107,17 @@ public class PostService {
return listPostsByCategories(null, null, null);
}
public List<Post> listPostsByViews(Integer page, Integer pageSize) {
Pageable pageable = null;
if (page != null && pageSize != null) {
pageable = PageRequest.of(page, pageSize);
}
if (pageable != null) {
return postRepository.findByStatusOrderByViewsDesc(PostStatus.PUBLISHED, pageable);
}
return postRepository.findByStatusOrderByViewsDesc(PostStatus.PUBLISHED);
}
public List<Post> listPostsByCategories(java.util.List<Long> categoryIds,
Integer page,
Integer pageSize) {