Skip to content

Commit a05def3

Browse files
committed
Feat: 게시글 수정 API 구현
1 parent 809b6e2 commit a05def3

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

src/main/java/com/back/domain/board/controller/PostController.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,4 +65,20 @@ public ResponseEntity<RsData<PostDetailResponse>> getPost(
6565
response
6666
));
6767
}
68+
69+
// 게시글 수정
70+
@PutMapping("/{postId}")
71+
public ResponseEntity<RsData<PostResponse>> updatePost(
72+
@PathVariable Long postId,
73+
@RequestBody @Valid PostRequest request,
74+
@AuthenticationPrincipal CustomUserDetails user
75+
) {
76+
PostResponse response = postService.updatePost(postId, request, user.getUserId());
77+
return ResponseEntity
78+
.status(HttpStatus.OK)
79+
.body(RsData.success(
80+
"게시글이 수정되었습니다.",
81+
response
82+
));
83+
}
6884
}

src/main/java/com/back/domain/board/entity/Post.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ public Post(User user, String title, String content) {
4141
}
4242

4343
// -------------------- 비즈니스 메서드 --------------------
44+
// 게시글 업데이트
45+
public void update(String title, String content) {
46+
this.title = title;
47+
this.content = content;
48+
}
49+
4450
// 카테고리 업데이트
4551
public void updateCategories(List<PostCategory> categories) {
4652
this.postCategoryMappings.clear();

src/main/java/com/back/domain/board/service/PostService.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,35 @@ public PostDetailResponse getPost(Long postId) {
8080
// 응답 반환
8181
return PostDetailResponse.from(post);
8282
}
83+
84+
/**
85+
* 게시글 수정 서비스
86+
* 1. Post 조회
87+
* 2. 작성자 검증
88+
* 3. Post 업데이트 (제목, 내용, 카테고리)
89+
* 4. PostResponse 반환
90+
*/
91+
public PostResponse updatePost(Long postId, PostRequest request, Long userId) {
92+
// Post 조회
93+
Post post = postRepository.findById(postId)
94+
.orElseThrow(() -> new CustomException(ErrorCode.POST_NOT_FOUND));
95+
96+
// 작성자 검증
97+
if (!post.getUser().getId().equals(userId)) {
98+
throw new CustomException(ErrorCode.POST_NO_PERMISSION);
99+
}
100+
101+
// Post 업데이트
102+
post.update(request.title(), request.content());
103+
104+
// Category 매핑 업데이트
105+
List<PostCategory> categories = postCategoryRepository.findAllById(request.categoryIds());
106+
if (categories.size() != request.categoryIds().size()) {
107+
throw new CustomException(ErrorCode.CATEGORY_NOT_FOUND);
108+
}
109+
post.updateCategories(categories);
110+
111+
// 응답 반환
112+
return PostResponse.from(post);
113+
}
83114
}

0 commit comments

Comments
 (0)