Skip to content

Commit

Permalink
[fix] 게시물 가져오기 거리 기반으로 가져오기
Browse files Browse the repository at this point in the history
  • Loading branch information
jainefer committed Dec 21, 2024
1 parent 4790776 commit d953d34
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,17 @@ public BaseResponse<PostsResponse.ViewAllResultResponse> getPostsController(
@RequestParam(value = "category", required = false) String category,
@Parameter(name = "page", description = "페이지 번호 (1부터 시작)", example = "1", in = ParameterIn.QUERY, required = false)
@RequestParam(value = "page", required = false, defaultValue = "1") int page,
@Parameter(name = "order", description = "정렬 방향 (asc: 오름차순, desc: 내림차순)", example = "desc", in = ParameterIn.QUERY, required = false)
@Parameter(name = "order", description = "정렬 방향 (asc: 오름차순, desc: 내림차순)", example = "asc", in = ParameterIn.QUERY, required = false)
@RequestParam(value = "order", required = false, defaultValue = "desc") String order,
@Parameter(name = "sortBy", description = "정렬 기준 (예: price, createdAt, likeCount)", example = "createdAt", in = ParameterIn.QUERY, required = true)
@Parameter(name = "sortBy", description = "정렬 기준 (예: price, createdAt, likeCount,distance)", example = "distance", in = ParameterIn.QUERY, required = true)
@RequestParam(value = "sortBy", required = true, defaultValue = "accuracy") String sortBy
) {

String userId = "";
if (MDC.get(JWTUtil.MDC_USER_ID) != null) {
userId = MDC.get(JWTUtil.MDC_USER_ID);
}
Sort.Direction direction = "asc".equalsIgnoreCase(order) ? Sort.Direction.ASC : Sort.Direction.DESC;
return new BaseResponse<>(postsService.ViewAllPostService(category, page, direction, sortBy));
return new BaseResponse<>(postsService.ViewAllPostService(category, page, direction, sortBy,userId));
}

@Operation(summary = "게시물 검색", description = "게시물 검색 API")
Expand All @@ -65,9 +68,9 @@ public BaseResponse<PostsResponse.ViewAllResultResponse> getSearchPostsControlle
@RequestParam(value = "category", required = false) String category,
@Parameter(name = "page", description = "페이지 번호 (1부터 시작)", example = "1", in = ParameterIn.QUERY, required = false)
@RequestParam(value = "page", required = false, defaultValue = "1") int page,
@Parameter(name = "order", description = "정렬 방향 (asc: 오름차순, desc: 내림차순)", example = "desc", in = ParameterIn.QUERY, required = false)
@Parameter(name = "order", description = "정렬 방향 (asc: 오름차순, desc: 내림차순)", example = "asc", in = ParameterIn.QUERY, required = false)
@RequestParam(value = "order", required = false, defaultValue = "desc") String order,
@Parameter(name = "sortBy", description = "정렬 기준 (예: price, createdAt, likeCount)", example = "createdAt", in = ParameterIn.QUERY, required = true)
@Parameter(name = "sortBy", description = "정렬 기준 (예: price, createdAt, likeCount,distance)", example = "distance", in = ParameterIn.QUERY, required = true)
@RequestParam(value = "sortBy", required = true, defaultValue = "accuracy") String sortBy,
@Parameter(name = "keyword", description = "검색 키워드(예: 6인용+텐트)", in = ParameterIn.QUERY, required = true)
@RequestParam(value = "keyword", required = true) String keyword) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import org.springframework.data.domain.Sort;
import site.billbill.apiserver.api.borrowPosts.dto.request.PostsRequest;
import site.billbill.apiserver.api.borrowPosts.dto.response.PostsResponse;
import site.billbill.apiserver.model.user.UserLocationJpaEntity;

import java.util.List;

public interface PostsService {
PostsResponse.UploadResponse uploadPostService(PostsRequest.UploadRequest request, String userId);

PostsResponse.ViewAllResultResponse ViewAllPostService(String category, int page, Sort.Direction direction, String orderType);
PostsResponse.ViewAllResultResponse ViewAllPostService(String category, int page, Sort.Direction direction, String orderType, String userId);

PostsResponse.ViewPostResponse ViewPostService(String postId, String userId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ public PostsResponse.UploadResponse uploadPostService(PostsRequest.UploadRequest
}

public PostsResponse.ViewAllResultResponse ViewAllPostService(
String category, int page, Sort.Direction direction, String orderType) {

String category, int page, Sort.Direction direction, String orderType,String userId) {
UserLocationJpaEntity userLocation = userLocationReposity.findByUserId(userId).orElse(null);
Pageable pageable = createPageable(page, direction, orderType);
log.info(category);
List<PostsResponse.Post> items = findAndConvertItems(category, pageable, null);
List<PostsResponse.Post> items = findAndConvertItems(category, pageable, null,userLocation);
return PostsConverter.toViewAllList(items);
}

Expand Down Expand Up @@ -175,10 +175,10 @@ public String UpdatePostService(String postId, String userId, PostsRequest.Uploa

@Transactional
public PostsResponse.ViewAllResultResponse ViewSearchPostService(String userId, String category, int page, Sort.Direction direction, String orderType, String keyword, boolean state) {
UserJpaEntity user = userRepository.findById(userId).orElse(null);
UserLocationJpaEntity userLocation= userLocationReposity.findByUserId(userId).orElse(null);

Pageable pageable = createPageable(page, direction, orderType);
List<PostsResponse.Post> items = findAndConvertItems(category, pageable, keyword);
List<PostsResponse.Post> items = findAndConvertItems(category, pageable, keyword,userLocation);
//사용자가 검색어 저장을 허용했을 경우
String tempKeyword = keyword.replaceAll("\\+", " ");
// if(state){
Expand Down Expand Up @@ -330,6 +330,7 @@ private Pageable createPageable(int page, Sort.Direction direction, String order
case "price" -> "price";
case "createdAt" -> "createdAt";
case "likeCount" -> "likeCount";
case "distance"->"distance";
default -> "createdAt"; // 기본 정렬
};
//정렬 순서
Expand All @@ -342,9 +343,9 @@ private Pageable createPageable(int page, Sort.Direction direction, String order
);
}

private List<PostsResponse.Post> findAndConvertItems(String category, Pageable pageable, String keyword) {
private List<PostsResponse.Post> findAndConvertItems(String category, Pageable pageable, String keyword,UserLocationJpaEntity userLocation) {
// Repository 호출
Page<ItemsJpaEntity> itemsPage = itemsRepository.findItemsWithConditions(category, pageable, null, keyword);
Page<ItemsJpaEntity> itemsPage = itemsRepository.findItemsWithConditions(category, pageable, null, keyword,userLocation.getLatitude(),userLocation.getLongitude());

// 빈 결과 체크
if (itemsPage.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

public interface ItemDslRepository {

Page<ItemsJpaEntity> findItemsWithConditions(String category, Pageable pageable, String sortField,String keyword);
Page<ItemsJpaEntity> findItemsWithConditions(String category, Pageable pageable, String sortField,String keyword,Double latitude,Double longitude);

List<PostHistoryResponse> getPostHistory(String userId, Pageable pageable);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.Expressions;

import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
Expand All @@ -30,11 +31,11 @@ public class ItemDslRepositoryImpl implements ItemDslRepository {
private final JPAQueryFactory queryFactory;

@Override
public Page<ItemsJpaEntity> findItemsWithConditions(String category, Pageable pageable, String sortField, String keyword) {
public Page<ItemsJpaEntity> findItemsWithConditions(String category, Pageable pageable, String sortField, String keyword,Double latitude,Double longitude) {
QItemsJpaEntity items = QItemsJpaEntity.itemsJpaEntity;
QItemsBorrowJpaEntity borrow = QItemsBorrowJpaEntity.itemsBorrowJpaEntity;
QItemsCategoryJpaEntity categoryEntity = QItemsCategoryJpaEntity.itemsCategoryJpaEntity;

QItemsLocationJpaEntity QItemsLocation = QItemsLocationJpaEntity.itemsLocationJpaEntity;

JPAQuery<ItemsJpaEntity> query = queryFactory.selectFrom(items)
.leftJoin(items.category, categoryEntity).fetchJoin() // 명시적 Fetch Join
Expand Down Expand Up @@ -70,6 +71,20 @@ public Page<ItemsJpaEntity> findItemsWithConditions(String category, Pageable pa
orderSpecifier = order.isAscending() ? items.createdAt.asc() : items.createdAt.desc();
case "likeCount" ->
orderSpecifier = order.isAscending() ? items.likeCount.asc() : items.likeCount.desc();
case "distance" -> {
if (latitude != null && longitude != null) {
// 거리 계산식
NumberExpression<Double> distanceExpression = Expressions.numberTemplate(
Double.class,
"ST_Distance_Sphere(POINT({0}, {1}), POINT({2}, {3}))",
QItemsLocation.latitude, QItemsLocation.longitude, latitude, longitude
);
orderSpecifier = order.isAscending() ? distanceExpression.asc() : distanceExpression.desc();
} else {
log.warn("Latitude와 Longitude가 필요합니다.");
return;
}
}
default -> {
log.warn("Invalid sort field: {}", order.getProperty());
return;
Expand Down

0 comments on commit d953d34

Please sign in to comment.