Skip to content

Commit

Permalink
Merge pull request #90 from dongkyun0713/dongkyun
Browse files Browse the repository at this point in the history
코드 리팩토링
  • Loading branch information
dongkyun0713 authored Feb 26, 2024
2 parents d84e447 + 404023a commit 0c49ce8
Show file tree
Hide file tree
Showing 7 changed files with 96 additions and 114 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ public enum ErrorCode {
DUPLICATED_EMAIL(HttpStatus.BAD_REQUEST, "중복된 이메일입니다."),
DUPLICATED_NICKNAME(HttpStatus.BAD_REQUEST, "중복된 닉네임입니다."),
DUPLICATED_STUDENT_NO(HttpStatus.BAD_REQUEST, "중복된 학번입니다."),
MISMATCH_AUTHOR(HttpStatus.BAD_REQUEST, "권한이 없습니다."),
ALREADY_ACCEPTED_ANSWER(HttpStatus.BAD_REQUEST, "이미 채택된 답변이 존재합니다."),
INSUFFICIENT_EXPERIENCE(HttpStatus.BAD_REQUEST, "차감할 경험치가 부족합니다."),
INVALID_ACCESS(HttpStatus.BAD_REQUEST, "잘못된 접근입니다."),

/* 401 UNAUTHORIZED : 인증되지 않은 사용자 */
INVALID_AUTH_TOKEN(HttpStatus.UNAUTHORIZED, "인증 토큰이 유효하지 않습니다."),
Expand All @@ -27,10 +31,9 @@ public enum ErrorCode {
PROFILE_IMAGE_NOT_FOUND(HttpStatus.NOT_FOUND, "사용자의 프로필 이미지를 찾을 수 없습니다."),
QUESTION_NOT_FOUND(HttpStatus.NOT_FOUND, "질문을 찾을 수 없습니다."),
ANSWER_NOT_FOUND(HttpStatus.NOT_FOUND, "답변을 찾을 수 없습니다."),
MISMATCH_AUTHOR(HttpStatus.BAD_REQUEST, "권한이 없습니다."),
ALREADY_ACCEPTED_ANSWER(HttpStatus.BAD_REQUEST, "이미 채택된 답변이 존재합니다."),
INSUFFICIENT_EXPERIENCE(HttpStatus.BAD_REQUEST, "차감할 경험치가 부족합니다."),
NO_SEARCH_RESULT(HttpStatus.NOT_FOUND, "검색 결과가 없습니다.");
NO_SEARCH_RESULT(HttpStatus.NOT_FOUND, "검색 결과가 없습니다."),
POST_NOT_FOUND(HttpStatus.NOT_FOUND, "게시물이 존재하지 않습니다."),
REVIEW_NOT_FOUND(HttpStatus.NOT_FOUND, "댓글이 존재하지 않습니다.");

private final HttpStatus httpStatus;
private final String message;
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

import com.example.titto_backend.matchingBoard.domain.matchingBoard.MatchingPost;
import com.example.titto_backend.matchingBoard.domain.review.MatchingPostReview;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MatchingPostReviewRepository extends JpaRepository<MatchingPostReview, Long> {
List<MatchingPostReview> findAllByMatchingPost(MatchingPost matchingPost);

void deleteAllByMatchingPost(MatchingPost matchingPost);

Integer countByMatchingPost(MatchingPost matchingPost);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.example.titto_backend.auth.domain.User;
import com.example.titto_backend.auth.repository.UserRepository;
import com.example.titto_backend.common.exception.CustomException;
import com.example.titto_backend.common.exception.ErrorCode;
import com.example.titto_backend.matchingBoard.domain.matchingBoard.Category;
import com.example.titto_backend.matchingBoard.domain.matchingBoard.MatchingPost;
import com.example.titto_backend.matchingBoard.domain.matchingBoard.Status;
Expand All @@ -18,7 +20,6 @@
import jakarta.servlet.http.HttpServletResponse;
import java.security.Principal;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -33,34 +34,28 @@ public class MatchingPostService {
@Transactional
public MatchingPostCreateResponseDto createMatchingPost(Principal principal,
MatchingPostCreateRequestDto matchingPostCreateRequestDto) {
String userEmail = principal.getName();
User user = userRepository.findByEmail(userEmail).orElseThrow(
() -> new IllegalArgumentException("존재하지 않는 사용자입니다"));

User user = getCurrentUser(principal);
MatchingPost matchingPost = matchingPostCreateRequestDto.toEntity(user);
matchingPostRepository.save(matchingPost);

return MatchingPostCreateResponseDto.of(matchingPost);
}

// 게시물 조회
@Transactional(readOnly = true)
public MatchingPostResponseDto getMatchingPostByMatchingPostId(Long matchingPostId, HttpServletRequest request,
HttpServletResponse response) {
MatchingPost matchingPost = matchingPostRepository.findById(matchingPostId).orElseThrow(
() -> new IllegalArgumentException("존재하지 않는 게시물입니다"));

Integer reviewCount = matchingPostReviewRepository.findAllByMatchingPost(matchingPost).size(); // 댓글 수
countViews(matchingPost, request, response); // 조회수 업데이트
matchingPostRepository.save(matchingPost);

MatchingPost matchingPost = findMatchingPostById(matchingPostId);
Integer reviewCount = matchingPostReviewRepository.countByMatchingPost(matchingPost);
updatePostViews(request, response, matchingPostId);
return MatchingPostResponseDto.of(matchingPost, reviewCount);
}

// 게시물 삭제
@Transactional
public MatchingPostDeleteResponseDto deleteMatchingPostByMatchingPostId(Long matchingPostId) {
MatchingPost matchingPost = matchingPostRepository.findById(matchingPostId).orElseThrow(
() -> new IllegalArgumentException("존재하지 않는 게시물입니다"));
MatchingPost matchingPost = findMatchingPostById(matchingPostId);

matchingPostReviewRepository.deleteAllByMatchingPost(matchingPost);
matchingPostRepository.delete(matchingPost);
return MatchingPostDeleteResponseDto.of(matchingPostId);
Expand All @@ -70,14 +65,10 @@ public MatchingPostDeleteResponseDto deleteMatchingPostByMatchingPostId(Long mat
@Transactional
public MatchingPostUpdateResponseDto updateMatchingPost(Long matchingPostId, Principal principal,
MatchingPostUpdateRequestDto matchingPostUpdateRequestDto) {
MatchingPost matchingPost = matchingPostRepository.findById(matchingPostId).orElseThrow(
() -> new IllegalArgumentException("존재하지 않는 게시물입니다"));

String userEmail = principal.getName();
User user = userRepository.findByEmail(userEmail).orElseThrow(
() -> new IllegalArgumentException("존재하지 않는 사용자입니다"));
MatchingPost matchingPost = findMatchingPostById(matchingPostId);

Integer reviewCount = matchingPostReviewRepository.findAllByMatchingPost(matchingPost).size(); // 댓글 수
User user = getCurrentUser(principal);
Integer reviewCount = matchingPostReviewRepository.countByMatchingPost(matchingPost);

if (user.getNickname().equals(matchingPost.getUser().getNickname())) {
// 게시물 내용 수정
Expand All @@ -92,47 +83,56 @@ public MatchingPostUpdateResponseDto updateMatchingPost(Long matchingPostId, Pri
matchingPost,
reviewCount);
} else {
throw new AuthorizationServiceException("잘못된 접근입니다");
throw new CustomException(ErrorCode.INVALID_ACCESS);
}
}

// 게시글 조회수 연산
private void countViews(MatchingPost matchingPost, HttpServletRequest request, HttpServletResponse response) {
Cookie cookie = null;
private void increaseViewCount(MatchingPost matchingPost) {
matchingPost.updateViewCount();
matchingPostRepository.save(matchingPost);
}

private void createOrUpdatePostViewsCookie(HttpServletRequest request, HttpServletResponse response,
MatchingPost matchingPost) {
Cookie[] cookies = request.getCookies();
if (matchingPost != null) {
String postId = "POST[" + matchingPost.getMatchingPostId() + "]";
if (cookies != null) {
// 쿠키 중에서 "postViews" 쿠키를 찾습니다.
for (Cookie oldCookie : cookies) {
if (oldCookie.getName().equals("postViews")) {
cookie = oldCookie;
break;
}
String postId = "POST[" + matchingPost.getMatchingPostId() + "]";
Cookie postViewsCookie = null;
if (cookies != null) {
for (Cookie oldCookie : cookies) {
if (oldCookie.getName().equals("postViews")) {
postViewsCookie = oldCookie;
break;
}
}
if (cookie != null) {
// "postViews" 쿠키가 있는 경우
if (!cookie.getValue().contains(postId)) {
// 쿠키의 값에 현재 게시물의 ID가 없다면 조회수를 증가시키고 쿠키를 업데이트합니다.
matchingPost.updateViewCount();
cookie.setValue(cookie.getValue() + postId);
}
} else {
// "postViews" 쿠키가 없는 경우 쿠키를 생성하고 조회수를 증가시킵니다.
matchingPost.updateViewCount();
cookie = new Cookie("postViews", postId);
}
if (postViewsCookie == null) {
postViewsCookie = new Cookie("postViews", postId);
} else {
if (!postViewsCookie.getValue().contains(postId)) {
postViewsCookie.setValue(postViewsCookie.getValue() + postId);
}
response.addCookie(setCookieValue(cookie)); // 쿠키를 응답에 추가합니다.
matchingPostRepository.save(matchingPost); // 게시물을 저장하여 조회수를 업데이트합니다.
}
postViewsCookie.setPath("/");
postViewsCookie.setMaxAge(60 * 60 * 24);
response.addCookie(postViewsCookie);
}

public void updatePostViews(HttpServletRequest request, HttpServletResponse response, Long matchingPostId) {
MatchingPost matchingPost = findMatchingPostById(matchingPostId);
increaseViewCount(matchingPost);
createOrUpdatePostViewsCookie(request, response, matchingPost);
}

private User getCurrentUser(Principal principal) {
String userEmail = principal.getName();
return userRepository.findByEmail(userEmail)
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));
}

// 쿠키 설정
private Cookie setCookieValue(Cookie cookie) {
cookie.setPath("/");
cookie.setMaxAge(60 * 60 * 24);
return cookie;
private MatchingPost findMatchingPostById(Long matchingPostId) {
return matchingPostRepository.findById(matchingPostId)
.orElseThrow(() -> new CustomException(ErrorCode.POST_NOT_FOUND));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.example.titto_backend.auth.domain.User;
import com.example.titto_backend.auth.repository.UserRepository;
import com.example.titto_backend.common.exception.CustomException;
import com.example.titto_backend.common.exception.ErrorCode;
import com.example.titto_backend.matchingBoard.domain.matchingBoard.MatchingPost;
import com.example.titto_backend.matchingBoard.domain.review.MatchingPostReview;
import com.example.titto_backend.matchingBoard.dto.request.matchingPostReviewRequest.MatchingPostReviewCreateRequestDto;
Expand All @@ -12,15 +14,13 @@
import com.example.titto_backend.matchingBoard.dto.response.matchingPostReviewResponse.MatchingPostReviewUpdateResponseDto;
import com.example.titto_backend.matchingBoard.repository.matchingBoard.MatchingPostRepository;
import com.example.titto_backend.matchingBoard.repository.review.MatchingPostReviewRepository;
import java.security.Principal;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

@Service
@RequiredArgsConstructor
public class MatchingPostReviewService {
Expand All @@ -30,43 +30,42 @@ public class MatchingPostReviewService {

// 생성
@Transactional
public MatchingPostReviewCreateResponseDto createReview(Principal principal, MatchingPostReviewCreateRequestDto matchingPostReviewCreateRequestDto) {
String userEmail = principal.getName();
User user = userRepository.findByEmail(userEmail).orElseThrow(
() -> new IllegalArgumentException("존재하지 않는 사용자입니다"));
public MatchingPostReviewCreateResponseDto createReview(Principal principal,
MatchingPostReviewCreateRequestDto matchingPostReviewCreateRequestDto) {
User user = getCurrentUser(principal);

MatchingPostReview matchingPostReview = MatchingPostReview.builder()
.matchingPost(matchingPostRepository.findById(matchingPostReviewCreateRequestDto.getPostId())
.orElseThrow(() -> new NoSuchElementException("게시물이 존재하지 않습니다.")))
.orElseThrow(() -> new CustomException(ErrorCode.POST_NOT_FOUND)))
.reviewAuthor(user)
.content(matchingPostReviewCreateRequestDto.getContent())
.build();
return new MatchingPostReviewCreateResponseDto(matchingPostReviewRepository.save(matchingPostReview));
}

// 조회
public List<MatchingPostReviewResponseDto> getAllMatchingBoardReviewsByPostId(Long postId) {
MatchingPost matchingPost = matchingPostRepository.findById(postId)
.orElseThrow(() -> new NoSuchElementException("게시물이 존재하지 않습니다."));
.orElseThrow(() -> new CustomException(ErrorCode.POST_NOT_FOUND));

List<MatchingPostReview> matchingPostReviews = matchingPostReviewRepository.findAllByMatchingPost(matchingPost);
List<MatchingPostReviewResponseDto> responses = new ArrayList<>();
for (MatchingPostReview matchingPostReview : matchingPostReviews) {
responses.add(new MatchingPostReviewResponseDto(matchingPostReview));
}
return responses;

return matchingPostReviews.stream()
.map(MatchingPostReviewResponseDto::new)
.collect(Collectors.toList());
}


// 수정
@Transactional
public MatchingPostReviewUpdateResponseDto updateReview(Principal principal, MatchingPostReviewUpdateRequestDto matchingPostReviewUpdateRequestDto) {
String userEmail = principal.getName();
User user = userRepository.findByEmail(userEmail).orElseThrow(
() -> new IllegalArgumentException("존재하지 않는 사용자입니다"));
public MatchingPostReviewUpdateResponseDto updateReview(Principal principal,
MatchingPostReviewUpdateRequestDto matchingPostReviewUpdateRequestDto) {
User user = getCurrentUser(principal);

MatchingPostReview matchingPostReview = MatchingPostReview.builder()
.review_id(matchingPostReviewUpdateRequestDto.getReviewId())
.matchingPost(matchingPostRepository.findById(matchingPostReviewUpdateRequestDto.getPostId())
.orElseThrow(() -> new NoSuchElementException("게시물이 존재하지 않습니다.")))
.orElseThrow(() -> new CustomException(ErrorCode.POST_NOT_FOUND)))
.reviewAuthor(user)
.content(matchingPostReviewUpdateRequestDto.getContent())
.build();
Expand All @@ -78,8 +77,14 @@ public MatchingPostReviewUpdateResponseDto updateReview(Principal principal, Mat
@Transactional
public MatchingPostReviewDeleteResponseDto deleteReviewByReviewId(Long reviewId) {
MatchingPostReview matchingPostReview = matchingPostReviewRepository.findById(reviewId).orElseThrow(
() -> new NoSuchElementException("존재하지 않는 댓글입니다"));
() -> new CustomException(ErrorCode.REVIEW_NOT_FOUND));
matchingPostReviewRepository.delete(matchingPostReview);
return MatchingPostReviewDeleteResponseDto.of(reviewId);
}

private User getCurrentUser(Principal principal) {
String userEmail = principal.getName();
return userRepository.findByEmail(userEmail)
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ public static class Response {
@Schema(description = "수정 날짜")
private LocalDateTime updateDate;

@Schema(description = "사용자 레벨")
private Integer level;

@Schema(description = "사용자 레벨")
private String profile;

public Response(Question question) {
this.id = question.getId();
this.authorId = question.getAuthor().getId();
Expand All @@ -106,6 +112,8 @@ public Response(Question question) {
this.viewCount = question.getViewCount();
this.createDate = question.getCreateDate();
this.updateDate = question.getUpdateDate();
this.level = question.getAuthor().getLevel();
this.profile = question.getAuthor().getProfile();
}
}

Expand Down

0 comments on commit 0c49ce8

Please sign in to comment.