Skip to content
Merged
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
24 changes: 20 additions & 4 deletions src/main/java/com/back/domain/board/post/entity/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ public void addPostCategoryMapping(PostCategoryMapping mapping) {
this.postCategoryMappings.add(mapping);
}

public void removePostCategoryMapping(PostCategoryMapping mapping) {
this.postCategoryMappings.remove(mapping);
}

public void addLike(PostLike like) {
this.postLikes.add(like);
}
Expand Down Expand Up @@ -93,11 +97,23 @@ public void update(String title, String content) {
this.content = content;
}

// TODO: 진짜로 바뀐 카테고리만 추가/삭제하도록 개선
/** 카테고리 일괄 업데이트 */
public void updateCategories(List<PostCategory> categories) {
this.postCategoryMappings.clear();
categories.forEach(category -> new PostCategoryMapping(this, category));
public void updateCategories(List<PostCategory> newCategories) {
List<PostCategory> currentCategories = this.getCategories();

// 제거 대상
List<PostCategoryMapping> toRemove = this.getPostCategoryMappings().stream()
.filter(mapping -> !newCategories.contains(mapping.getCategory()))
.toList();

// 추가 대상
List<PostCategory> toAdd = newCategories.stream()
.filter(category -> !currentCategories.contains(category))
.toList();

// 실행
toRemove.forEach(this::removePostCategoryMapping);
toAdd.forEach(category -> new PostCategoryMapping(this, category));
}

/** 좋아요 수 증가 */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,18 @@ public PostResponse createPost(PostRequest request, Long userId) {
// Post 생성
Post post = new Post(user, request.title(), request.content(), request.thumbnailUrl());

// Post 저장
Post saved = postRepository.save(post);

// Category 매핑
if (request.categoryIds() != null) {
List<PostCategory> categories = postCategoryRepository.findAllById(request.categoryIds());
if (categories.size() != request.categoryIds().size()) {
throw new CustomException(ErrorCode.CATEGORY_NOT_FOUND);
}
post.updateCategories(categories);
saved.updateCategories(categories);
}

// Post 저장 및 응답 반환
Post saved = postRepository.save(post);
return PostResponse.from(saved);
}

Expand Down