-
Notifications
You must be signed in to change notification settings - Fork 20
[3주차] 이교형/[feat] 게시글 도메인 API 구현 #128
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
Open
LGH0507
wants to merge
3
commits into
Leets-Official:이교형/main
Choose a base branch
from
LGH0507:이교형/3주차
base: 이교형/main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
The head ref may contain hidden characters: "\uC774\uAD50\uD615/3\uC8FC\uCC28"
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
12 changes: 12 additions & 0 deletions
12
src/main/java/com/example/leets_project/common/exception/GeneralException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package com.example.leets_project.common.exception; | ||
|
|
||
| import com.example.leets_project.common.response.ErrorCode; | ||
| import lombok.AllArgsConstructor; | ||
| import lombok.Getter; | ||
|
|
||
| @Getter | ||
| @AllArgsConstructor | ||
| public class GeneralException extends RuntimeException{ | ||
|
|
||
| private ErrorCode errorCode; | ||
| } |
62 changes: 62 additions & 0 deletions
62
src/main/java/com/example/leets_project/common/exception/GlobalExceptionHandler.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| package com.example.leets_project.common.exception; | ||
|
|
||
| import com.example.leets_project.common.response.ErrorCode; | ||
| import com.example.leets_project.common.response.GlobalResponse; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.context.support.DefaultMessageSourceResolvable; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.web.bind.MethodArgumentNotValidException; | ||
| import org.springframework.web.bind.MissingRequestHeaderException; | ||
| import org.springframework.web.bind.annotation.ExceptionHandler; | ||
| import org.springframework.web.bind.annotation.RestControllerAdvice; | ||
|
|
||
| import java.util.stream.Collectors; | ||
|
|
||
| @RestControllerAdvice | ||
| @Slf4j | ||
| public class GlobalExceptionHandler { | ||
|
|
||
| // 커스텀 예외 | ||
| @ExceptionHandler(GeneralException.class) | ||
| public ResponseEntity<GlobalResponse> handleGeneralException(GeneralException e) { | ||
| log.warn("GeneralException: [{}] {}", e.getErrorCode().getCode(), e.getErrorCode().getMessage()); | ||
| return GlobalResponse.onFailure(e.getErrorCode()); | ||
| } | ||
| // Validation 에러 | ||
| @ExceptionHandler(MethodArgumentNotValidException.class) | ||
| public ResponseEntity<GlobalResponse> handleValidationExceptions(MethodArgumentNotValidException e) { | ||
| String errorDetail = e.getBindingResult() | ||
| .getFieldErrors() | ||
| .stream() | ||
| .map(error -> "[" + error.getField() + "]: " + error.getDefaultMessage()) | ||
| .collect(Collectors.joining(", ")); | ||
|
|
||
| log.warn("Validation Failed: {}", errorDetail); | ||
| return GlobalResponse.onFailure(ErrorCode.VALIDATION_FAILED, errorDetail); | ||
| } | ||
|
|
||
| // JSON 처리 에러 | ||
| @ExceptionHandler({com.fasterxml.jackson.core.JsonParseException.class, | ||
| com.fasterxml.jackson.databind.JsonMappingException.class}) | ||
| public ResponseEntity<GlobalResponse> handleJsonException(Exception e) { | ||
| log.error("JSON 처리 오류: {}", e.getMessage()); | ||
|
|
||
| return GlobalResponse.onFailure(ErrorCode.VALIDATION_FAILED, "잘못된 JSON 형식입니다."); | ||
| } | ||
|
|
||
| // X-USER-ID 헤더 누락 | ||
| @ExceptionHandler(MissingRequestHeaderException.class) | ||
| public ResponseEntity<GlobalResponse> handleMissingHeader(MissingRequestHeaderException e) { | ||
| log.warn("필수 헤더 누락 - {}", e.getHeaderName()); | ||
|
|
||
| return GlobalResponse.onFailure(ErrorCode.UNAUTHORIZED, "필수 헤더가 누락되었습니다."); | ||
| } | ||
|
|
||
| // 모든 예외 | ||
| @ExceptionHandler(Exception.class) | ||
| public ResponseEntity<GlobalResponse> handleGenericException(Exception e) { | ||
| log.error("Unexpected Error", e); | ||
|
|
||
| return GlobalResponse.onFailure(ErrorCode.INTERNAL_ERROR); | ||
| } | ||
| } |
34 changes: 34 additions & 0 deletions
34
src/main/java/com/example/leets_project/common/response/ErrorCode.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| package com.example.leets_project.common.response; | ||
|
|
||
| import lombok.AllArgsConstructor; | ||
| import lombok.Getter; | ||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| @Getter | ||
| @AllArgsConstructor | ||
| public enum ErrorCode { | ||
|
|
||
| // COMMON | ||
| VALIDATION_FAILED(HttpStatus.BAD_REQUEST, "COMMON_4000", "유효하지 않은 값입니다."), | ||
| INVALID_INPUT(HttpStatus.BAD_REQUEST, "COMMON_4001", "잘못된 입력입니다."), | ||
| METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, "COMMON_4002", "허용되지 않은 요청입니다."), | ||
| INTERNAL_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON_5000", "서버 오류입니다."), | ||
|
|
||
| // AUTH | ||
| UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "AUTH_4000", "인증이 필요합니다."), | ||
| FORBIDDEN(HttpStatus.FORBIDDEN, "AUTH_4001", "접근 권한이 없습니다."), | ||
|
|
||
| // USER | ||
| USER_NOT_FOUND(HttpStatus.NOT_FOUND, "USER_4040", "사용자를 찾을 수 없습니다."), | ||
| USER_EMAIL_ALREADY_EXISTS(HttpStatus.CONFLICT, "USER_4001", "이미 사용 중인 이메일입니다."), | ||
| USER_NICKNAME_ALREADY_EXISTS(HttpStatus.CONFLICT, "USER_4002", "이미 사용 중인 닉네임입니다."), | ||
| // POST | ||
| POST_NOT_FOUND(HttpStatus.NOT_FOUND, "POST_4040", "게시글을 찾을 수 없습니다."), | ||
| POST_INVALID(HttpStatus.BAD_REQUEST, "POST_4001", "게시글 입력값이 올바르지 않습니다."), | ||
| POST_FORBIDDEN(HttpStatus.FORBIDDEN, "POST_4003", "작성자만 수정/삭제할 수 있습니다."); | ||
|
|
||
| private final HttpStatus status; | ||
| private final String code; | ||
| private final String message; | ||
|
|
||
| } |
46 changes: 46 additions & 0 deletions
46
src/main/java/com/example/leets_project/common/response/GlobalResponse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| package com.example.leets_project.common.response; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonInclude; | ||
| import com.fasterxml.jackson.annotation.JsonPropertyOrder; | ||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.ResponseEntity; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| @JsonPropertyOrder({"isSuccess", "code", "message", "result"}) | ||
| public class GlobalResponse { | ||
|
|
||
| private final Boolean isSuccess; // 성공, 실패 여부 | ||
|
|
||
| private final String code; // 상태 코드 | ||
|
|
||
| private final String message; // 구체적인 메시지 | ||
|
|
||
| @JsonInclude(JsonInclude.Include.NON_NULL) | ||
| private final Object result; //반환할 객체 | ||
|
|
||
| public static ResponseEntity<GlobalResponse> onSuccess(SuccessCode successCode, Object result){ | ||
| return new ResponseEntity<>( | ||
| new GlobalResponse(true, successCode.getCode(), successCode.getMessage(), result), | ||
| successCode.getStatus()); | ||
| } | ||
|
|
||
| public static ResponseEntity<GlobalResponse> onSuccess(SuccessCode successCode){ | ||
| return new ResponseEntity<>( | ||
| new GlobalResponse(true, successCode.getCode(), successCode.getMessage(), null), | ||
| successCode.getStatus()); | ||
| } | ||
|
|
||
| public static ResponseEntity<GlobalResponse> onFailure(ErrorCode errorCode, Object result){ | ||
| return new ResponseEntity<>( | ||
| new GlobalResponse(false, errorCode.getCode(), errorCode.getMessage(), result), | ||
| errorCode.getStatus()); | ||
| } | ||
|
|
||
| public static ResponseEntity<GlobalResponse> onFailure(ErrorCode errorCode){ | ||
| return new ResponseEntity<>( | ||
| new GlobalResponse(false, errorCode.getCode(), errorCode.getMessage(), null), | ||
| errorCode.getStatus()); | ||
| } | ||
| } |
23 changes: 23 additions & 0 deletions
23
src/main/java/com/example/leets_project/common/response/SuccessCode.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| package com.example.leets_project.common.response; | ||
|
|
||
| import lombok.AllArgsConstructor; | ||
| import lombok.Getter; | ||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| @Getter | ||
| @AllArgsConstructor | ||
| public enum SuccessCode { | ||
|
|
||
| // USER | ||
| USER_CREATE(HttpStatus.CREATED, "USER_2010", "유저 생성 성공"), | ||
| // POST | ||
| POST_LIST(HttpStatus.OK, "POST_2000", "게시글 목록 조회 성공"), | ||
| POST_DETAIL(HttpStatus.OK, "POST_2001", "게시글 조회 성공"), | ||
| POST_UPDATE(HttpStatus.OK, "POST_2002", "게시글 수정 성공"), | ||
| POST_DELETE(HttpStatus.OK, "POST_2003", "게시글 삭제 성공"), | ||
| POST_CREATE(HttpStatus.CREATED, "POST_2010", "게시글 생성 성공"); | ||
|
|
||
| private final HttpStatus status; | ||
| private final String code; | ||
| private final String message; | ||
| } |
6 changes: 1 addition & 5 deletions
6
src/main/java/com/example/leets_project/domain/comment/Comment.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
7 changes: 7 additions & 0 deletions
7
src/main/java/com/example/leets_project/domain/post/repository/PostRepository.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package com.example.leets_project.domain.post.repository; | ||
|
|
||
| import com.example.leets_project.domain.post.entity.Post; | ||
| import org.springframework.data.jpa.repository.JpaRepository; | ||
|
|
||
| public interface PostRepository extends JpaRepository<Post, Long> { | ||
| } |
111 changes: 111 additions & 0 deletions
111
src/main/java/com/example/leets_project/domain/post/service/PostService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| package com.example.leets_project.domain.post.service; | ||
|
|
||
| import com.example.leets_project.common.exception.GeneralException; | ||
| import com.example.leets_project.common.response.ErrorCode; | ||
| import com.example.leets_project.domain.post.entity.Post; | ||
| import com.example.leets_project.domain.post.repository.PostRepository; | ||
| import com.example.leets_project.domain.post.web.dto.*; | ||
| import com.example.leets_project.domain.user.User; | ||
| import com.example.leets_project.domain.user.repository.UserRepository; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.data.domain.Page; | ||
| import org.springframework.data.domain.PageRequest; | ||
| import org.springframework.data.domain.Sort; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| @Service | ||
| @RequiredArgsConstructor | ||
| @Transactional(readOnly = true) | ||
| public class PostService { | ||
|
|
||
| private final PostRepository postRepository; | ||
| private final UserRepository userRepository; | ||
|
|
||
| private static final int MIN_PAGE = 0; | ||
| private static final int MAX_PAGE = 10; | ||
|
|
||
| // 1. 게시글 생성 | ||
| @Transactional | ||
| public PostCreateResponse createPost(Long currentUserId, PostCreateRequest request) { | ||
| // 사용자 존재 확인 | ||
| User user = findUserOrThrow(currentUserId); | ||
|
|
||
| Post post = Post.builder() | ||
| .user(user) | ||
| .title(request.getTitle()) | ||
| .content(request.getContent()) | ||
| .description(request.getDescription()) | ||
| .build(); | ||
|
|
||
| Post savedPost = postRepository.save(post); | ||
|
|
||
| return PostCreateResponse.from(savedPost); | ||
| } | ||
|
|
||
| // 2. 게시글 목록 조회 (페이징) | ||
| public Page<PostListResponse> getPosts(int page, int size) { | ||
|
|
||
| validatePageRange(page); | ||
| PageRequest pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt")); | ||
|
|
||
| return postRepository.findAll(pageable) | ||
| .map(PostListResponse::from); | ||
| } | ||
|
|
||
| // 3. 게시글 상세 조회 | ||
| public PostDetailResponse getPostDetail(Long postId) { | ||
|
|
||
| Post post = findPostOrThrow(postId); | ||
|
|
||
| return PostDetailResponse.from(post); | ||
| } | ||
|
|
||
| // 4. 게시글 수정 | ||
| @Transactional | ||
| public PostUpdateResponse updatePost(Long postId, Long currentUserId, PostUpdateRequest request) { | ||
|
|
||
| Post post = findPostOrThrow(postId); | ||
|
|
||
| post.updatePost( | ||
| request.getTitle(), | ||
| request.getContent(), | ||
| request.getDescription(), | ||
| currentUserId | ||
| ); | ||
|
|
||
| return PostUpdateResponse.from(post); | ||
| } | ||
|
|
||
| // 5. 게시글 삭제 | ||
| @Transactional | ||
| public PostDeleteResponse deletePost(Long postId, Long currentUserId) { | ||
|
|
||
| Post post = findPostOrThrow(postId); | ||
|
|
||
| post.validateOwner(currentUserId); | ||
|
|
||
| postRepository.delete(post); | ||
|
|
||
| return PostDeleteResponse.of(postId); | ||
| } | ||
|
|
||
| // 공통 검증 로직 | ||
| // 게시글 조회 | ||
| private Post findPostOrThrow(Long postId) { | ||
| return postRepository.findById(postId) | ||
| .orElseThrow(() -> new GeneralException(ErrorCode.POST_NOT_FOUND)); | ||
| } | ||
|
|
||
| // 사용자 조회 | ||
| private User findUserOrThrow(Long userId) { | ||
| return userRepository.findById(userId) | ||
| .orElseThrow(() -> new GeneralException(ErrorCode.USER_NOT_FOUND)); | ||
| } | ||
|
|
||
| private void validatePageRange(int page) { | ||
| if (page < MIN_PAGE || page > MAX_PAGE) { | ||
| throw new GeneralException(ErrorCode.POST_INVALID); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저는 게시글이 존재하는지, 사용자가 존재하는지에 대한 검증 코드를 매번 메소드마다 따로 작성했었는데, 이렇게 자주 사용하는 검증 코드를 메소드로 만들어두고 쓰면 가독성도 더 좋고 확장하기도 편할 것 같습니다. 고생 많으셨습니다!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
존재하지 않는 id인 경우에 커스텀 예외로 던지고, 전역 핸들러에서 처리하는 구조도 좋은 것 같습니다. 코드 참고해서 피드백 주신 부분 보완해보겠습니다!