Skip to content

Commit

Permalink
Merge pull request #55 from WooHyeopHa/kyukyu/post
Browse files Browse the repository at this point in the history
[Refactoring] 모집글 CRUD 리팩토링
  • Loading branch information
lalabulla authored Dec 22, 2024
2 parents ae79f4c + 6710025 commit 5324ec2
Show file tree
Hide file tree
Showing 32 changed files with 399 additions and 336 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static ArtOneResponse toDto(Art art, boolean isLiked, boolean isStared, b
return ArtOneResponse.builder()
.poster(art.getPoster())
.title(art.getTitle())
.genre(art.getArtType().getInfo())
.genre(art.getGenre().getDescription())
.age(art.getAge())
.place(art.getPlace())
.startDate(art.getStartDate())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public static List<ArtRandomResponse> toDto(List<Art> artList) {
return artList.stream()
.map(a -> ArtRandomResponse.builder()
.artId(a.getId())
.genre(a.getArtType().getInfo())
.genre(a.getGenre().getDescription())
.poster(a.getPoster()).build()).toList();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static ArtTumbnailResponse toDto(Art art) {
return ArtTumbnailResponse.builder()
.title(art.getTitle())
.place(art.getPlace())
.genre(art.getArtType().getInfo())
.genre(art.getGenre().getDescription())
.poster(art.getPoster())
.startDate(art.getStartDate())
.endDate(art.getEndDate())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ private static MapByArtResponse toDto(Art art){
.longitude(art.getLongitude())
.title(art.getTitle())
.artId(art.getId())
.genre(art.getArtType().getInfo())
.genre(art.getGenre().getDescription())
.poster(art.getPoster())
.startDate(art.getStartDate())
.endDate(art.getEndDate())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class Art {
private int randomId;
private String title;
@Enumerated(EnumType.STRING)
private ArtType artType;
private Genre genre;
private String location;
private String place;
private String startDate;
Expand Down Expand Up @@ -59,10 +59,10 @@ public class Art {
private List<ArtHistory> artHistories = new ArrayList<>();

@Builder
public Art(String title, int randomId, ArtType artType, String place, String startDate, String endDate, String startTime,String age) {
public Art(String title, int randomId, Genre genre, String place, String startDate, String endDate, String startTime, String age) {
this.title = title;
this.randomId = randomId;
this.artType = artType;
this.genre = genre;
this.place = place;
this.startDate = startDate;
this.endDate = endDate;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ public void setDetail(Details detail) {
this.detail = detail;
}

public Art toEntity(Infos.ArtType type) {
public Art toEntity(Infos.Genre genre) {

Art newArt = Art.builder()
.title(detail.title)
.randomId((int) (Math.random() * 100000000))
.artType(type)
.genre(genre)
.place(detail.place)
.startDate(detail.startDate)
.endDate(detail.endDate)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import java.util.List;

import static com.whh.findmuseapi.art.openApi.dto.ArtInfoResponse.*;
import static com.whh.findmuseapi.common.constant.Infos.ArtType.*;
import static com.whh.findmuseapi.common.constant.Infos.Genre.*;


@RequiredArgsConstructor
Expand Down Expand Up @@ -46,7 +46,7 @@ public void init() {
api2Entity(artProperties.getClassic(), DANCE_CLASSIC);
}

private void api2Entity(String category, Infos.ArtType type) {
private void api2Entity(String category, Infos.Genre type) {
// 1.ID리스트 불러오기
List<Db> idList = getIdList(category);
// 2. 상세정보 불러오기
Expand All @@ -60,7 +60,7 @@ private void api2Entity(String category, Infos.ArtType type) {
/**
* 엔티티 저장
*/
private void saveArt(List<ArtInfoDetailResponse> artDetailList, List<PlaceInfoDetailResponse> placeDetailList, Infos.ArtType type) {
private void saveArt(List<ArtInfoDetailResponse> artDetailList, List<PlaceInfoDetailResponse> placeDetailList, Infos.Genre type) {
for (int i = 0; i < artDetailList.size(); i++) {
Art newArt = artDetailList.get(i).toEntity(type);
placeDetailList.get(i).toEntity(newArt);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.whh.findmuseapi.art.repository;

import com.whh.findmuseapi.art.entity.Art;
import com.whh.findmuseapi.common.constant.Infos.ArtType;
import com.whh.findmuseapi.common.constant.Infos.Genre;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
Expand All @@ -12,16 +12,16 @@
public interface ArtRepository extends JpaRepository<Art, Long> {

@Query("select a from Art a left outer join a.artLikes al on al.user.id = :userId where a.startDate <= :date and a.artType in (:types) order by a.startDate desc")
List<Art> findArtByCondition(Long userId, String date, List<ArtType> types);
List<Art> findArtByCondition(Long userId, String date, List<Genre> types);

@Query("select a from Art a left outer join a.artLikes al on al.user.id = :userId where a.startDate <= :date and a.artType in (:types) order by a.star desc")
List<Art> findArtByConditionRank(Long userId, String date, List<ArtType> types);
List<Art> findArtByConditionRank(Long userId, String date, List<Genre> types);

// @Query(value = "select a from Art a left outer join a.artLikes al on al.user.id = :userId where a.artType = :type order by a.viewCnt, a.star desc limit 50")
// List<Art> findArtByRankAndGenre(Long userId, ArtType type);
// List<Art> findArtByRankAndGenre(Long userId, Genre type);
//
// @Query(value = "select a from Art a left outer join a.artLikes al on al.user.id = :userId where a.artType = :type order by a.viewCnt, a.star desc limit 5")
// List<Art> findArtByRankAndGenreSimple(Long userId, ArtType type);
// List<Art> findArtByRankAndGenreSimple(Long userId, Genre type);
//
// @Query("select a from Art a left outer join a.artLikes al on al.user.id = :userId order by a.viewCnt, a.star desc limit 50")
// List<Art> findArtByRankAll(Long userId);
Expand All @@ -31,7 +31,7 @@ public interface ArtRepository extends JpaRepository<Art, Long> {

// 취향 별 랜덤 추출 5개
@Query(value = "select * from Art a where a.art_type = :type and a.random_id >= floor(rand() * 100000000) limit 5", nativeQuery = true)
List<Art> findArtByGenre(ArtType type);
List<Art> findArtByGenre(Genre type);

// 취향 정보가 없을 때 랜덤 추출 5개
@Query(value = "select * from Art a where a.random_id >= floor(rand() * 100000000) limit 5", nativeQuery = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import com.whh.findmuseapi.art.repository.ArtHistoryRepository;
import com.whh.findmuseapi.art.repository.ArtLikeRepository;
import com.whh.findmuseapi.art.repository.ArtRepository;
import com.whh.findmuseapi.common.constant.Infos.ArtType;
import com.whh.findmuseapi.common.constant.Infos;
import com.whh.findmuseapi.common.constant.Infos.Genre;
import com.whh.findmuseapi.common.exception.CBadRequestException;
import com.whh.findmuseapi.common.exception.CInternalServerException;
import com.whh.findmuseapi.common.exception.CNotFoundException;
Expand Down Expand Up @@ -67,13 +68,13 @@ public ArtListResponse getArtByCondition(Long userId, String date, List<String>
if (genre == null) {
throw new CBadRequestException("잘못된 요청입니다. 장르를 입력해주세요");
}
List<ArtType> artTypes = genre.stream().map(ArtType::convert).toList();
List<Genre> genres = genre.stream().map(Infos.Genre::convertStringToGenre).toList();
userRepository.findById(userId).orElseThrow(() -> new CNotFoundException(userId + "은(는) 존재하지 않는 회원입니다."));

if (sort.equals("최신순")) {
return ArtListResponse.toDto(artRepository.findArtByCondition(userId, date, artTypes));
return ArtListResponse.toDto(artRepository.findArtByCondition(userId, date, genres));
}
return ArtListResponse.toDto(artRepository.findArtByConditionRank(userId, date, artTypes));
return ArtListResponse.toDto(artRepository.findArtByConditionRank(userId, date, genres));
}

/**
Expand Down Expand Up @@ -110,8 +111,8 @@ private List<ArtRandomResponse> getArtByRandAndGenre(User user) {
else {
// 취향 정보가 있는 경우
user.getTasteList().forEach(t -> {
ArtType artType = ArtType.convert(t.getTaste().getName());
randArtList.addAll(ArtRandomResponse.toDto(artRepository.findArtByGenre(artType)));
Infos.Genre genre = Infos.Genre.convertStringToGenre(t.getTaste().getName());
randArtList.addAll(ArtRandomResponse.toDto(artRepository.findArtByGenre(genre)));
});
}
return randArtList;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.whh.findmuseapi.common.annotation;

import jakarta.persistence.OptimisticLockException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.hibernate.StaleObjectStateException;
import org.springframework.core.annotation.Order;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Order(2147483646)
@Slf4j
public class OptimisticLockRetryAspect {
private static final int MAX_RETRIES = 1000;
private static final int RETRY_DELAY_MS = 100;

@Pointcut("@annotation(Retry)")
public void retry() {
}

@Around("retry()")
public Object retryOptimisticLock(ProceedingJoinPoint joinPoint) throws Throwable {
Exception exceptionHolder = null;
for (int attempt = 0; attempt < MAX_RETRIES; attempt++) {
try {
return joinPoint.proceed();
} catch (OptimisticLockException | ObjectOptimisticLockingFailureException | StaleObjectStateException e) {
log.info("Post 버전이 일치하지 않습니다. 재시도합니다.");
exceptionHolder = e;
Thread.sleep(RETRY_DELAY_MS);
}
}
throw exceptionHolder;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.whh.findmuseapi.common.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Retry {
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.whh.findmuseapi.common.exception.CBadRequestException;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.Arrays;

Expand All @@ -13,21 +12,22 @@ public class Infos {
public enum Gender {
MEN("남성"),
WOMEN("여성");
private final String info;

public static Gender convertStringToGender(String info) {
private final String description;

public static Gender convertStringToGender(String value) {
return Arrays.stream(Gender.values())
.filter(gender -> gender.info.equals(info))
.filter(gender -> gender.description.equals(value))
.findFirst()
.orElseThrow(() -> new CBadRequestException("유효하지 않은 성별 값이 입력되었습니다."));
.orElseThrow(() -> new CBadRequestException("Invalid SortType: " + value));
}
}

@RequiredArgsConstructor
public enum LoginType {
APPLE("애플 로그인");

private final String info;
private final String description;
}

@RequiredArgsConstructor
Expand All @@ -39,7 +39,7 @@ public enum Ages {
FOURTIES("40대"),
REST("50+");

private final String info;
private final String description;
}

@RequiredArgsConstructor
Expand All @@ -48,7 +48,7 @@ public enum InvieteStatus {
DENY("거절됨"),
Wait("대기중");

private final String info;
private final String description;
}

public enum Rating {
Expand All @@ -57,39 +57,35 @@ public enum Rating {

@RequiredArgsConstructor
@Getter
public enum ArtType {
public enum Genre {
MUSICAL_DRAMA("뮤지컬/연극"),
EXHIBITION("전시회"),
DANCE_CLASSIC("무용/클래식"),
CONCERT("콘서트");

private final String info;
public static ArtType convert(String info){
for (ArtType value : ArtType.values()) {
if (value.getInfo().equals(info)) {
return value;
}
}
throw new CBadRequestException("일치하는 장르가 없습니다. 다시 요청해주세요");
private final String description;
public static Genre convertStringToGenre(String value){
return Arrays.stream(Genre.values())
.filter(genre -> genre.description.equals(value))
.findFirst()
.orElseThrow(() -> new CBadRequestException("Invalid SortType: " + value));
}

}

@Getter
@RequiredArgsConstructor
public enum ReviewSortType {
public enum SortType {
LATEST("최신순"),
POPULAR("인기순");

private final String description;

public static ReviewSortType fromString(String value) {
for (ReviewSortType type : ReviewSortType.values()) {
if (type.getDescription().equals(value)) {
return type;
}
}
throw new IllegalArgumentException("Invalid ReviewSortType: " + value);
public static SortType convertStringToSortType(String value) {
return Arrays.stream(SortType.values())
.filter(sort -> sort.description.equals(value))
.findFirst()
.orElseThrow(()-> new CBadRequestException("Invalid SortType: " + value));
}
}

Expand Down
Loading

0 comments on commit 5324ec2

Please sign in to comment.