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: User 도메인 테스트 리팩토링 #33

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import lombok.Getter;
Expand All @@ -16,18 +15,9 @@
@Getter
public class BaseEntity {

@Column(
nullable = false,
insertable = false,
updatable = false,
columnDefinition = "datetime default CURRENT_TIMESTAMP")
@CreatedDate
protected LocalDateTime createdDate;

@Column(
nullable = false,
insertable = false,
columnDefinition = "datetime default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP")
@LastModifiedDate
private LocalDateTime updatedDate;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
Expand Down Expand Up @@ -53,4 +55,9 @@ public void addInterceptors(final InterceptorRegistry registry) {
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new AuthInfoArgumentResolver(authTokenManager));
}

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,8 @@ public static Pageable generateSimplePageable(int size) {
public static Pageable generateDateDescPageable(int size) {
return PageRequest.of(0, size, Sort.by(Sort.Direction.DESC, DATE));
}

public static Pageable generateDateAscPageable(int size) {
return PageRequest.of(0, size, Sort.by(Sort.Direction.ASC, DATE));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class RedisUtils {

private final RedisTemplate<String, Long> redisTemplate;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ public class LikeReviewService {
private final LikeReviewRepository likeReviewRepository;
private final RedisUtils redisUtils;

private Long updateLikeCountFromRedis(Long reviewId) {
Long likeCount = likeReviewRepository.countByReviewId(reviewId);
redisUtils.setData(reviewId, likeCount);
return likeCount;
}

@Transactional
public boolean executeLike(Long reviewId, Long userId) {
try {
Expand All @@ -41,10 +47,7 @@ public boolean executeLike(Long reviewId, Long userId) {

@Transactional
public boolean cancelLike(Long reviewId, Long userId) {
int deletedCount = likeReviewRepository.deleteByUserIdAndReviewId(userId, reviewId);
if (deletedCount == 0) {
return false;
}
likeReviewRepository.deleteByUserIdAndReviewId(userId, reviewId);

redisUtils.getData(reviewId)
.ifPresentOrElse(
Expand All @@ -56,7 +59,8 @@ public boolean cancelLike(Long reviewId, Long userId) {
}

public LikeReviewResponse checkIsLiking(Long userId, Long reviewId) {
return new LikeReviewResponse(existLikeReview(userId, reviewId));
boolean isLiking = likeReviewRepository.existsByUserIdAndReviewId(userId, reviewId);
return new LikeReviewResponse(isLiking);
}

public Long getLikeCount(Long reviewId) {
Expand All @@ -69,14 +73,4 @@ public List<Long> getLikeCounts(List<Long> reviewIds) {
.map(this::getLikeCount)
.toList();
}

private Long updateLikeCountFromRedis(Long reviewId) {
Long likeCount = likeReviewRepository.countByReviewId(reviewId);
redisUtils.setData(reviewId, likeCount);
return likeCount;
}

private boolean existLikeReview(Long userId, Long reviewId) {
return likeReviewRepository.existsByUserIdAndReviewId(userId, reviewId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,12 @@ public class ReviewFindService {

private final ReviewRepository reviewRepository;

public Review getById(Long id) {
return reviewRepository.findById(id)
.orElseThrow(() -> new WishHairException(ErrorCode.NOT_EXIST_KEY));
}

public Review findWithPhotosById(Long id) {
return reviewRepository.findWithPhotosById(id)
.orElseThrow(() -> new WishHairException(ErrorCode.NOT_EXIST_KEY));
}

public List<Review> findWithPhotosByUserId(Long userId) {
return reviewRepository.findWithPhotosByUserId(userId);
return reviewRepository.findWithPhotosByWriterId(userId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ public class ReviewSearchService {
private final ReviewQueryRepository reviewQueryRepository;
private final LikeReviewService likeReviewService;

private List<Long> fetchLikeCounts(List<Review> result) {
List<Long> reviewIds = result.stream().map(Review::getId).toList();
return likeReviewService.getLikeCounts(reviewIds);
}

/*리뷰 단건 조회*/
@AddisWriter
public ReviewDetailResponse findReviewById(Long userId, Long reviewId) {
Expand Down Expand Up @@ -87,9 +92,4 @@ public ResponseWrapper<ReviewResponse> findReviewByHairStyle(Long userId, Long h

return toWrappedReviewResponse(result, likeCounts);
}

private List<Long> fetchLikeCounts(List<Review> result) {
List<Long> reviewIds = result.stream().map(Review::getId).toList();
return likeReviewService.getLikeCounts(reviewIds);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
import com.inq.wishhair.wesharewishhair.hairstyle.domain.HairStyle;
import com.inq.wishhair.wesharewishhair.hairstyle.application.HairStyleFindService;
import com.inq.wishhair.wesharewishhair.photo.application.PhotoService;
import com.inq.wishhair.wesharewishhair.review.presentation.dto.request.ReviewCreateRequest;
import com.inq.wishhair.wesharewishhair.review.presentation.dto.request.ReviewUpdateRequest;
import com.inq.wishhair.wesharewishhair.review.application.dto.request.ReviewCreateRequest;
import com.inq.wishhair.wesharewishhair.review.application.dto.request.ReviewUpdateRequest;
import com.inq.wishhair.wesharewishhair.review.domain.entity.Contents;
import com.inq.wishhair.wesharewishhair.review.domain.entity.Review;
import com.inq.wishhair.wesharewishhair.review.domain.ReviewRepository;
Expand All @@ -37,12 +37,33 @@ public class ReviewService {
private final HairStyleFindService hairStyleFindService;
private final ApplicationEventPublisher eventPublisher;

private void validateIsWriter(Long userId, Review review) {
if (!review.isWriter(userId)) {
throw new WishHairException(ErrorCode.REVIEW_NOT_WRITER);
}
}

private List<String> refreshPhotos(Review review, List<MultipartFile> files) {
photoService.deletePhotosByReviewId(review);
return photoService.uploadPhotos(files);
}

private Review generateReview(ReviewCreateRequest request, List<String> photos, User user, HairStyle hairStyle) {
return Review.createReview(
user,
request.contents(),
request.score(),
photos,
hairStyle
);
}

@Transactional
public Long createReview(ReviewCreateRequest request, Long userId) {

List<String> photoUrls = photoService.uploadPhotos(request.getFiles());
List<String> photoUrls = photoService.uploadPhotos(request.files());
User user = userFindService.findByUserId(userId);
HairStyle hairStyle = hairStyleFindService.getById(request.getHairStyleId());
HairStyle hairStyle = hairStyleFindService.getById(request.hairStyleId());

Review review = generateReview(request, photoUrls, user, hairStyle);
eventPublisher.publishEvent(new PointChargeEvent(100, userId));
Expand All @@ -51,53 +72,38 @@ public Long createReview(ReviewCreateRequest request, Long userId) {
}

@Transactional
public void deleteReview(Long reviewId, Long userId) {
public boolean deleteReview(Long reviewId, Long userId) {
Review review = reviewFindService.findWithPhotosById(reviewId);
validateIsWriter(userId, review);

likeReviewRepository.deleteAllByReview(reviewId);
likeReviewRepository.deleteByReviewId(reviewId);
photoService.deletePhotosByReviewId(review);
reviewRepository.delete(review);

return true;
}

@Transactional
public void updateReview(ReviewUpdateRequest request, Long userId) {
Review review = reviewFindService.findWithPhotosById(request.getReviewId());
public boolean updateReview(ReviewUpdateRequest request, Long userId) {
Review review = reviewFindService.findWithPhotosById(request.reviewId());
validateIsWriter(userId, review);

Contents contents = new Contents(request.getContents());
List<String> storeUrls = refreshPhotos(review, request.getFiles());
review.updateReview(contents, request.getScore(), storeUrls);
Contents contents = new Contents(request.contents());
List<String> storeUrls = refreshPhotos(review, request.files());
review.updateReview(contents, request.score(), storeUrls);

return true;
}

@Transactional
public void deleteReviewByWriter(Long userId) {
public boolean deleteReviewByWriter(Long userId) {
List<Review> reviews = reviewFindService.findWithPhotosByUserId(userId);
List<Long> reviewIds = reviews.stream().map(Review::getId).toList();

likeReviewRepository.deleteAllByReviews(reviewIds);
likeReviewRepository.deleteByReviewIdIn(reviewIds);
photoService.deletePhotosByWriter(reviews);
reviewRepository.deleteAllByWriter(reviewIds);
}

private void validateIsWriter(Long userId, Review review) {
if (!review.isWriter(userId)) {
throw new WishHairException(ErrorCode.REVIEW_NOT_WRITER);
}
}
reviewRepository.deleteByIdIn(reviewIds);

private List<String> refreshPhotos(Review review, List<MultipartFile> files) {
photoService.deletePhotosByReviewId(review);
return photoService.uploadPhotos(files);
}

private Review generateReview(ReviewCreateRequest request, List<String> photos, User user, HairStyle hairStyle) {
return Review.createReview(
user,
request.getContents(),
request.getScore(),
photos,
hairStyle
);
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.inq.wishhair.wesharewishhair.review.application.dto.request;

import java.util.List;

import org.springframework.web.multipart.MultipartFile;

import com.inq.wishhair.wesharewishhair.review.domain.entity.Score;

import jakarta.validation.constraints.NotNull;

public record ReviewCreateRequest(
@NotNull
String contents,
@NotNull
Score score,
List<MultipartFile> files,
@NotNull
Long hairStyleId
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.inq.wishhair.wesharewishhair.review.application.dto.request;

import java.util.List;

import org.springframework.web.multipart.MultipartFile;

import com.inq.wishhair.wesharewishhair.review.domain.entity.Score;

import jakarta.validation.constraints.NotNull;

public record ReviewUpdateRequest(
@NotNull
Long reviewId,
@NotNull
String contents,
@NotNull
Score score,

List<MultipartFile> files
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ public record ReviewSimpleResponse(
public ReviewSimpleResponse(Review review) {
this(
review.getId(),
review.getContentsValue(),
review.getContentsValue(),
review.getWriter().getNicknameValue(),
review.getHairStyle().getName(),
review.getContentsValue()
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class ScoreConverter implements Converter<String, Score> {
@Override
public Score convert(String value) {
switch (value) {
case "0" -> {
case "0.0" -> {
return Score.S0;
}
case "0.5" -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@

import java.util.List;
import java.util.Optional;
import java.util.Set;

import org.springframework.data.repository.query.Param;

import com.inq.wishhair.wesharewishhair.review.domain.entity.Review;

Expand All @@ -18,14 +15,9 @@ public interface ReviewRepository {
Optional<Review> findWithPhotosById(Long id);

//회원 탈퇴를 위한 사용자가 작성한 리뷰 조회
List<Review> findWithPhotosByUserId(Long userId);
List<Review> findWithPhotosByWriterId(Long userId);

void deleteAllByWriter(List<Long> reviewIds);
void deleteByIdIn(List<Long> reviewIds);

void delete(Review review);

//reviewIds 에 해당되는 리뷰의 좋아요 수 조회
List<Integer> countLikeReviewByIdsOrderById(@Param("ids") Set<Long> reviewIds);

void updateLikeCountById(Long id, int likeCount);
}
Loading