Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REFACTOR] 검색 디렉토리 분리 및 쿼리 리팩토링 #341

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
7a6b4b5
refactor(search): 검색 기능 분리 및 elastic 서버 연결 유무에 따른 api 수정
ayoung-dev Dec 29, 2024
dafef89
test(search): 검색 기능 분리 및 elastic 서버 연결 유무에 따라 test 수정 및 추가
ayoung-dev Jan 9, 2025
bdc5ed3
test(search): import 수정
ayoung-dev Jan 9, 2025
666050f
test(search): controller test 수정
ayoung-dev Jan 10, 2025
6c22867
refactor(search): 커뮤니티 Document 필드 추가
ayoung-dev Jan 17, 2025
d2f91f5
refactor(search): 커뮤니티 검색 쿼리 수정
ayoung-dev Jan 17, 2025
ebb486d
test(search): 커뮤니티 검색 리팩토링에 따른 test 수정
ayoung-dev Jan 17, 2025
0838c3e
refactor(search): 커뮤니티 Document updatedAt 필드 추가
ayoung-dev Jan 17, 2025
3796e6b
refactor(search): 커뮤니티 게시글 findAll() -> findAllByDeletedFalse()
ayoung-dev Jan 17, 2025
c9c9b30
refactor(search): 개행 수정
ayoung-dev Jan 17, 2025
f3296ed
refactor(search): 커뮤니티 검색 test를 위한 delete 메서드 수정
ayoung-dev Jan 17, 2025
fe6faf5
feat(center): center id로 기관명 조회하는 로직 추가
ayoung-dev Jan 21, 2025
b8cf776
test(center): center id로 기관명 조회하는 로직 test 추가
ayoung-dev Jan 21, 2025
26997f6
refactor(search): community elastic search 검색 메서드명 변경
ayoung-dev Jan 21, 2025
a989a01
refactor(search): 커뮤니티 게시글 검색 쿼리 수정
ayoung-dev Jan 26, 2025
6399ad4
refactor(search): 봉사활동 모집글 document 필드 추가 및 responseDto에 fromDocument 추가
ayoung-dev Jan 26, 2025
7a75784
refactor(recruit_board): 기존 findAll() -> findAllByDeletedFalse() 수정
ayoung-dev Jan 26, 2025
d810858
refactor(search): 봉사활동 모집글 검색 쿼리 리팩토링
ayoung-dev Jan 26, 2025
21bbe8d
test(search): scheduler test 수정
ayoung-dev Jan 26, 2025
1d18ef3
refactor(search): 중복 코드 추출
ayoung-dev Jan 27, 2025
defbe5a
refactor(search): 미구현 코드 recruitboard로 이동
ayoung-dev Jan 27, 2025
6fe8f0f
test(search): 봉사활동 모집글 검색 쿼리 리팩토링에 따른 test 수정
ayoung-dev Jan 27, 2025
493f1b7
fix(search): search 디렉토리 커버리지 제외
ayoung-dev Jan 27, 2025
b9a1f57
refactor(search): 불필요한 코드 삭제
ayoung-dev Jan 27, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ def jacocoExcludePatterns = [
'**/event/**',
'**/*Aspect*',
'**/Aspect/*',
'**/utils/*'
'**/utils/*',
'**/search/**'
]

def jacocoExcludePatternsForVerify = [
Expand All @@ -161,7 +162,8 @@ def jacocoExcludePatternsForVerify = [
'*.*event*.*',
'*.*Aspect*',
'*.Aspect.*',
'*.utils.*'
'*.utils.*',
'*.search.*'
]

jacocoTestReport {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@ default boolean doesNotExistById(UUID id) {
List<CenterOverviewInfo> findCenterOverviewsByIds(List<UUID> ids);

void deleteAllInBatch();

String findNameById(UUID id);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.somemore.domains.center.repository.center;

import com.querydsl.core.types.Path;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
Expand Down Expand Up @@ -66,7 +67,27 @@ public void deleteAllInBatch() {
centerJpaRepository.deleteAllInBatch();
}

@Override
public String findNameById(UUID id) {
return findDynamicField(id, center.name)
.orElse(null);
}

private static BooleanExpression isNotDeleted() {
return center.deleted.isFalse();
}

private <T> Optional<T> findDynamicField(UUID id, Path<T> field) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 신기하네요 생각하지 못했던 방법이라 감탄했습니다


return Optional.ofNullable(
queryFactory
.select(field)
.from(center)
.where(
center.id.eq(id),
isNotDeleted()
)
.fetchOne()
);
}
Comment on lines +80 to +92
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋아요!
ByExp 혹은 ByCenterId 를 메서드 이름 뒤에 붙이는 건 어떨까요?

사실 저번에 동적 쿼리를 위한 헬퍼 메서드 만들다가 조건 개수나 정렬, 페이징 같은 것 때문에 시간이 부족해서 포기했었는데 이번 기회에 조금 더 생각해 볼 수 있을 것 같습니다~

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@ public void validateCenterExists(UUID id) {
}
}

@Override
public String getNameById(UUID id) {
String name = centerRepository.findNameById(id);

if (name == null || name.isBlank()) {
throw new BadRequestException(NOT_EXISTS_CENTER);
}

return name;
}

private Center getCenterById(UUID centerId) {
return centerRepository.findCenterById(centerId)
.orElseThrow(() -> new BadRequestException(NOT_EXISTS_CENTER.getMessage()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ public interface CenterQueryUseCase {
List<CenterOverviewInfo> getCenterOverviewsByIds(List<UUID> centerIds);

void validateCenterExists(UUID centerId);
String getNameById(UUID id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
public class CommunityBoardQueryApiController {

private final CommunityBoardQueryUseCase communityBoardQueryUseCase;
// private final CommunityBoardDocumentUseCase communityBoardDocumentUseCase;

@GetMapping("/community-boards")
@Operation(summary = "전체 커뮤니티 게시글 조회", description = "전체 커뮤니티 게시글 목록을 조회합니다.")
Expand All @@ -51,32 +50,6 @@ public ApiResponse<Page<CommunityBoardResponseDto>> getByWriterId(
);
}

// @GetMapping("/community-boards/search")
// @Operation(summary = "커뮤니티 게시글 키워드 검색", description = "키워드로 포함한 커뮤니티 게시글 목록을 조회합니다.")
// public ApiResponse<Page<CommunityBoardResponseDto>> getCommunityBoardsBySearch(
// String keyword,
// Pageable pageable
// ) {
// return ApiResponse.ok(
// 200,
// communityBoardDocumentUseCase.getCommunityBoardBySearch(keyword, pageable.getPageNumber()),
// "커뮤니티 게시글 검색 리스트 조회 성공"
// );
// }

@GetMapping("/community-boards/search")
@Operation(summary = "커뮤니티 게시글 키워드 검색", description = "키워드를 포함한 커뮤니티 게시글 목록을 조회합니다.")
public ApiResponse<Page<CommunityBoardResponseDto>> getCommunityBoardsBySearch(
@RequestParam String keyword,
Pageable pageable
) {
return ApiResponse.ok(
200,
communityBoardQueryUseCase.getCommunityBoards(keyword, pageable.getPageNumber()),
"커뮤니티 게시글 검색 리스트 조회 성공"
);
}

@GetMapping("/community-board/{id}")
@Operation(summary = "커뮤니티 게시글 상세 조회", description = "커뮤니티 게시글의 상세 정보를 조회합니다.")
public ApiResponse<CommunityBoardDetailResponseDto> getById(
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import static lombok.AccessLevel.PROTECTED;


@Getter
@NoArgsConstructor(access = PROTECTED)
@Entity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.fasterxml.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.somemore.domains.community.repository.mapper.CommunityBoardView;
import com.somemore.domains.search.domain.CommunityBoardDocument;
import io.swagger.v3.oas.annotations.media.Schema;

import java.time.LocalDateTime;
Expand All @@ -12,9 +13,9 @@
public record CommunityBoardResponseDto(
@Schema(description = "커뮤니티 게시글 ID", example = "12")
Long id,
@Schema(description = "커뮤니티 게시글 ID", example = "12")
@Schema(description = "커뮤니티 게시글 제목", example = "11/29 OO도서관 봉사 같이 갈 사람 모집합니다.")
String title,
@Schema(description = "작성자(봉사자) ID", example = "123e4567-e89b-12d3-a456-426614174000")
@Schema(description = "작성자(봉사자) 닉네임", example = "나는야 봉사왕")
String writerNickname,
@Schema(description = "커뮤니티 게시글 생성 일시", example = "2023-12-02T11:00:00")
LocalDateTime createdAt
Expand All @@ -27,5 +28,13 @@ public static CommunityBoardResponseDto from(CommunityBoardView board) {
board.communityBoard().getCreatedAt()
);
}
}

public static CommunityBoardResponseDto fromDocument(CommunityBoardDocument board) {
return new CommunityBoardResponseDto(
board.getId(),
board.getTitle(),
board.getWriterNickname(),
board.getCreatedAt()
);
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import com.somemore.domains.community.domain.CommunityBoard;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface CommunityBoardJpaRepository extends JpaRepository<CommunityBoard, Long> {
boolean existsByIdAndDeletedFalse(Long id);
List<CommunityBoard> findAllByDeletedFalse();
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,13 @@

public interface CommunityBoardRepository {
CommunityBoard save(CommunityBoard communityBoard);

Optional<CommunityBoard> findById(Long id);

Page<CommunityBoardView> findCommunityBoards(String keyword, Pageable pageable);

Page<CommunityBoardView> findByWriterId(UUID writerId, Pageable pageable);

boolean existsById(Long id);

default boolean doesNotExistById(Long id) {
return !existsById(id);
}

void deleteAllInBatch();

// Page<CommunityBoardView> findByCommunityBoardsContaining(String keyword, Pageable pageable);
// void saveDocuments(List<CommunityBoard> communityBoards);
List<CommunityBoard> findAll();
// void deleteDocument(Long id);
List<CommunityBoard> findAllByDeletedFalse();
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ public class CommunityBoardRepositoryImpl implements CommunityBoardRepository {

private final JPAQueryFactory queryFactory;
private final CommunityBoardJpaRepository communityBoardJpaRepository;
// private final CommunityBoardDocumentRepository documentRepository;

private static final QCommunityBoard communityBoard = QCommunityBoard.communityBoard;
private static final QVolunteer volunteer = QVolunteer.volunteer;
Expand Down Expand Up @@ -87,47 +86,6 @@ public boolean existsById(Long id) {
return communityBoardJpaRepository.existsByIdAndDeletedFalse(id);
}

// @Override
// public Page<CommunityBoardView> findByCommunityBoardsContaining(String keyword, Pageable pageable) {
// List<CommunityBoardDocument> boardDocuments = getBoardDocuments(keyword);
//
// List<Long> boardIds = boardDocuments.stream()
// .map(CommunityBoardDocument::getId)
// .toList();
//
// List<CommunityBoardView> content = getCommunityBoardsQuery()
// .where(communityBoard.id.in(boardIds)
// .and(isNotDeleted()))
// .offset(pageable.getOffset())
// .limit(pageable.getPageSize())
// .fetch();
//
// JPAQuery<Long> countQuery = queryFactory
// .select(communityBoard.count())
// .from(communityBoard)
// .join(volunteer).on(communityBoard.writerId.eq(volunteer.id))
// .where(communityBoard.id.in(boardIds)
// .and(isNotDeleted()));
//
// return PageableExecutionUtils.getPage(content, pageable, countQuery::fetchOne);
// }

// @Override
// public void saveDocuments(List<CommunityBoard> communityBoards) {
// List<CommunityBoardDocument> communityBoardDocuments = convertEntityToDocuments(communityBoards);
// documentRepository.saveAll(communityBoardDocuments);
// }

// @Override
// public void deleteDocument(Long id) {
// documentRepository.deleteById(id);
// }

@Override
public List<CommunityBoard> findAll() {
return communityBoardJpaRepository.findAll();
}

@Override
public void deleteAllInBatch() {
communityBoardJpaRepository.deleteAllInBatch();
Expand All @@ -143,19 +101,10 @@ private JPAQuery<CommunityBoardView> getCommunityBoardsQuery() {
.orderBy(communityBoard.createdAt.desc());
}

// private List<CommunityBoardDocument> convertEntityToDocuments(List<CommunityBoard> communityBoards) {
// List<CommunityBoardDocument> communityBoardDocuments = new ArrayList<>();
//
// for (CommunityBoard communityboard : communityBoards) {
// CommunityBoardDocument document = CommunityBoardDocument.builder()
// .id(communityboard.getId())
// .title(communityboard.getTitle())
// .content(communityboard.getContent())
// .build();
// communityBoardDocuments.add(document);
// }
// return communityBoardDocuments;
// }
@Override
public List<CommunityBoard> findAllByDeletedFalse() {
return communityBoardJpaRepository.findAllByDeletedFalse();
}

private BooleanExpression isNotDeleted() {
return communityBoard.deleted.eq(false);
Expand All @@ -170,12 +119,4 @@ private BooleanExpression keywordEq(String keyword) {
? communityBoard.title.containsIgnoreCase(keyword)
: null;
}

// private List<CommunityBoardDocument> getBoardDocuments(String keyword) {
//
// if (keyword == null || keyword.isEmpty()) {
// return documentRepository.findAll();
// }
// return documentRepository.findIdsByTitleOrContentContaining(keyword);
// }
}

This file was deleted.

Loading
Loading