Skip to content

Commit

Permalink
Feat: 게시글 조회시 좋아요 유무 기능 추가하기 (#73)
Browse files Browse the repository at this point in the history
* #70 - feat: `QueryDsl` 설정 추가

게시글 조회 시 좋아요 유무를 알아야 하는데
이때 QueryDsl 을 사용하여 조회한다.

* #70 - feat: LAZY 설정 빠진 부분 추가

* #70 - feat: 게시글 조회시 좋아요 여부를 확인하는 api 기능 추가

* #70 - test: 추가된 로직 테스트 코드 작성
  • Loading branch information
GGHDMS authored Feb 5, 2024
1 parent 82452de commit 6657265
Show file tree
Hide file tree
Showing 13 changed files with 152 additions and 13 deletions.
6 changes: 6 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ dependencies {

implementation 'org.json:json:20231013'

// QueryDsl
implementation 'com.querydsl:querydsl-jpa:5.0.0:jakarta'
annotationProcessor "com.querydsl:querydsl-apt:5.0.0:jakarta"
annotationProcessor "jakarta.annotation:jakarta.annotation-api"
annotationProcessor "jakarta.persistence:jakarta.persistence-api"

compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.mysql:mysql-connector-j'

Expand Down
19 changes: 19 additions & 0 deletions src/main/java/cotato/bookitlist/config/QueryDslConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package cotato.bookitlist.config;

import com.querydsl.jpa.impl.JPAQueryFactory;
import jakarta.persistence.EntityManager;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor
public class QueryDslConfig {

private final EntityManager em;

@Bean
public JPAQueryFactory queryFactory() {
return new JPAQueryFactory(em);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,10 @@ public ResponseEntity<PostListResponse> getAllPost(
@GetMapping
public ResponseEntity<PostListResponse> searchPost(
@IsValidIsbn @RequestParam String isbn13,
@PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable
@PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable,
@AuthenticationPrincipal AuthDetails details
) {
return ResponseEntity.ok(postService.searchPost(isbn13, pageable));
return ResponseEntity.ok(postService.searchPost(isbn13, pageable, details));
}

@GetMapping("/count")
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/cotato/bookitlist/post/domain/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ public class Post extends BaseEntity {
@Column(name = "post_id")
private Long id;

@ManyToOne
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;

@ManyToOne
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "book_id")
private Book book;

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/cotato/bookitlist/post/domain/PostLike.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ public class PostLike {
@Column(name = "post_like_id")
private Long id;

@ManyToOne
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;

@ManyToOne
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;

Expand Down
6 changes: 4 additions & 2 deletions src/main/java/cotato/bookitlist/post/dto/PostDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ public record PostDto(
String title,
String content,
int likeCount,
int viewCount
int viewCount,
boolean liked
) {

public static PostDto from(Post entity) {
Expand All @@ -20,7 +21,8 @@ public static PostDto from(Post entity) {
entity.getTitle(),
entity.getContent(),
entity.getLikeCount(),
entity.getViewCount()
entity.getViewCount(),
false
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,14 @@ public static PostListResponse from(Page<Post> page) {
page.stream().map(PostDto::from).toList()
);
}

public static PostListResponse fromDto(Page<PostDto> dtoPage) {
return new PostListResponse(
(int) dtoPage.getTotalElements(),
dtoPage.getTotalPages(),
dtoPage.getNumber(),
dtoPage.getSize(),
dtoPage.stream().toList()
);
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package cotato.bookitlist.post.repository;

import cotato.bookitlist.post.domain.Post;
import cotato.bookitlist.post.repository.querydsl.PostRepositoryCustom;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository<Post, Long> {
public interface PostRepository extends PostRepositoryCustom, JpaRepository<Post, Long> {
Page<Post> findByBook_Isbn13(String isbn13, Pageable pageable);

int countByBook_Isbn13(String isbn13);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package cotato.bookitlist.post.repository.querydsl;

import cotato.bookitlist.post.dto.PostDto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface PostRepositoryCustom {
Page<PostDto> findWithLikedByIsbn13(String isbn13, Long memberId, Pageable pageable);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package cotato.bookitlist.post.repository.querydsl;

import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import cotato.bookitlist.post.dto.PostDto;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.support.PageableExecutionUtils;

import java.util.List;

import static cotato.bookitlist.post.domain.QPost.post;
import static cotato.bookitlist.post.domain.QPostLike.postLike;

@RequiredArgsConstructor
public class PostRepositoryCustomImpl implements PostRepositoryCustom {

private final JPAQueryFactory queryFactory;

@Override
public Page<PostDto> findWithLikedByIsbn13(String isbn13, Long memberId, Pageable pageable) {
List<PostDto> result = queryFactory
.select(
Projections.constructor(
PostDto.class,
post.id,
post.member.id,
post.book.id,
post.title,
post.content,
post.likeCount,
post.viewCount,
Expressions.cases()
.when(isLikedByMember(memberId, post.id))
.then(true)
.otherwise(false)
.as("liked")
)
)
.from(post)
.where(post.book.isbn13.eq(isbn13))
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.fetch();

JPAQuery<Long> countQuery = queryFactory
.select(post.count())
.from(post)
.where(post.book.isbn13.eq(isbn13))
.from(post);

return PageableExecutionUtils.getPage(result, pageable, countQuery::fetchOne);
}

private BooleanExpression isLikedByMember(Long memberId, NumberPath<Long> postId) {
return JPAExpressions.selectOne()
.from(postLike)
.where(postLike.member.id.eq(memberId)
.and(postLike.post.id.eq(postId)))
.exists();
}
}
9 changes: 7 additions & 2 deletions src/main/java/cotato/bookitlist/post/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import cotato.bookitlist.book.domain.entity.Book;
import cotato.bookitlist.book.repository.BookRepository;
import cotato.bookitlist.config.security.jwt.AuthDetails;
import cotato.bookitlist.member.domain.Member;
import cotato.bookitlist.member.repository.MemberRepository;
import cotato.bookitlist.post.domain.Post;
Expand Down Expand Up @@ -58,8 +59,12 @@ public PostListResponse getAllPost(Pageable pageable) {
}

@Transactional(readOnly = true)
public PostListResponse searchPost(String isbn13, Pageable pageable) {
return PostListResponse.from(postRepository.findByBook_Isbn13(isbn13, pageable));
public PostListResponse searchPost(String isbn13, Pageable pageable, AuthDetails details) {
if (details == null) {
return PostListResponse.from(postRepository.findByBook_Isbn13(isbn13, pageable));
}

return PostListResponse.fromDto(postRepository.findWithLikedByIsbn13(isbn13, details.getId(), pageable));
}

@Transactional(readOnly = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,24 @@ void givenIsbn13_whenSearchingPost_thenReturnPostListResponse() throws Exception
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.totalResults").value(4))
.andExpect(jsonPath("$.postList[1].liked").value(false))
;
}

@Test
@WithCustomMockUser
@DisplayName("로그인한 유저가 isbn13을 이용해 게시글을 조회한다.")
void givenIsbn13WithLogin_whenSearchingPost_thenReturnPostListResponse() throws Exception {
//given
String isbn13 = "9788931514810";

//when & then
mockMvc.perform(get("/posts")
.param("isbn13", isbn13)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.totalResults").value(4))
.andExpect(jsonPath("$.postList[1].liked").value(true))
;
}

Expand Down
4 changes: 2 additions & 2 deletions src/test/resources/data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ VALUES ('[email protected]', 'test', 'test', 'KAKAO', 0, false, CURRENT_TIMESTAMP,
('[email protected]', 'test2', 'test2', 'KAKAO', 0, false, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

INSERT INTO post (member_id, book_id, title, content, like_count, view_count, deleted)
VALUES (1, 1, 'postTitle', 'postContent', 1, 0, false),
(2, 1, 'postTitle1', 'Content', 0, 0, false),
VALUES (1, 1, 'postTitle', 'postContent', 0, 0, false),
(2, 1, 'postTitle1', 'Content', 2, 0, false),
(2, 1, 'postTitle2', '제목', 0, 0, false),
(2, 1, 'postTitle3', 'post', 0, 0, false),
(2, 2, 'posTitle', 'ptent', 0, 0, false),
Expand Down

0 comments on commit 6657265

Please sign in to comment.