Skip to content

Commit 2b57c18

Browse files
authored
[FIX] 게시글 작성하기 보완
2 parents dd95068 + d765d48 commit 2b57c18

3 files changed

Lines changed: 77 additions & 44 deletions

File tree

src/main/java/com/example/FixLog/domain/post/Post.java

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -79,22 +79,4 @@ public class Post {
7979
@OneToMany(mappedBy = "postId", cascade = CascadeType.ALL, orphanRemoval = true)
8080
private List<PostLike> postLikes = new ArrayList<>();
8181

82-
public Post(Member userId, String postTitle, String coverImage, String problem, String errorMessage,
83-
String environment, String reproduceCode, String solutionCode, String causeAnalysis,
84-
String referenceLink, String extraContent, LocalDateTime createdAt, LocalDateTime editedAt){
85-
this.userId = userId;
86-
this.postTitle = postTitle;
87-
this.coverImage = coverImage;
88-
this.problem = problem;
89-
this.errorMessage = errorMessage;
90-
this.environment = environment;
91-
this.reproduceCode = reproduceCode;
92-
this.solutionCode = solutionCode;
93-
this.causeAnalysis = causeAnalysis;
94-
this.referenceLink = referenceLink;
95-
this.extraContent = extraContent;
96-
this.createdAt = createdAt;
97-
this.editedAt = editedAt;
98-
// 게시글 태그
99-
}
10082
}

src/main/java/com/example/FixLog/exception/ErrorCode.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ public enum ErrorCode {
2222
ACCESS_DENIED(HttpStatus.FORBIDDEN, "권한이 없습니다."),
2323
TAG_NOT_FOUND(HttpStatus.NOT_FOUND, "없는 태그 번호입니다."),
2424
SORT_NOT_EXIST(HttpStatus.BAD_REQUEST, "사용할 수 없는 정렬입니다."),
25-
INVALID_PASSWORD(HttpStatus.UNAUTHORIZED, "비밀번호가 일치하지 않습니다.");
25+
INVALID_PASSWORD(HttpStatus.UNAUTHORIZED, "비밀번호가 일치하지 않습니다."),
26+
REQUIRED_TAGS_MISSING(HttpStatus.BAD_REQUEST, "태그를 선택해주세요."),
27+
REQUIRED_CONTENT_MISSING(HttpStatus.BAD_REQUEST, "필수 본문이 입력되지 않았습니다.");
2628

2729
private final HttpStatus status;
2830
private final String message;

src/main/java/com/example/FixLog/service/PostService.java

Lines changed: 74 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import com.example.FixLog.domain.post.Post;
88
import com.example.FixLog.domain.post.PostTag;
99
import com.example.FixLog.domain.tag.Tag;
10+
import com.example.FixLog.domain.tag.TagCategory;
1011
import com.example.FixLog.dto.post.PostDto;
1112
import com.example.FixLog.dto.post.PostRequestDto;
1213
import com.example.FixLog.dto.post.PostResponseDto;
@@ -22,10 +23,11 @@
2223

2324
import java.time.LocalDate;
2425
import java.time.LocalDateTime;
25-
import java.util.List;
26-
import java.util.Optional;
26+
import java.util.*;
2727
import java.util.stream.Collectors;
2828

29+
import static java.util.stream.Collectors.toList;
30+
2931
@Service
3032
public class PostService {
3133
private final PostRepository postRepository;
@@ -58,40 +60,87 @@ public String getDefaultImage(String image){
5860
@Transactional
5961
public void createPost(PostRequestDto postRequestDto){
6062
Member member = memberService.getCurrentMemberInfo();
61-
6263
String coverImageUrl = postRequestDto.getCoverImageUrl();
6364

64-
// Todo : 북마크 카테고리별로 선택 제한 두기
65+
// 북마크 카테고리별로 선택 제한 두기
66+
List<Tag> tags = fetchAndValidateTags(postRequestDto.getTags());
6567

6668
// 게시글 발행
67-
Post newPost = new Post(
68-
member,
69-
postRequestDto.getPostTitle(),
70-
coverImageUrl,
71-
postRequestDto.getProblem(),
72-
postRequestDto.getErrorMessage(),
73-
postRequestDto.getEnvironment(),
74-
postRequestDto.getReproduceCode(),
75-
postRequestDto.getSolutionCode(),
76-
postRequestDto.getCauseAnalysis(),
77-
postRequestDto.getReferenceLink(),
78-
postRequestDto.getExtraContent(),
79-
LocalDateTime.now(),
80-
LocalDateTime.now()
81-
);
69+
validatePost(postRequestDto); // 필수 항목 다 입력되었는지 확인
70+
Post newPost = Post.builder()
71+
.userId(member)
72+
.postTitle(postRequestDto.getPostTitle())
73+
.coverImage(coverImageUrl)
74+
.problem(postRequestDto.getProblem())
75+
.errorMessage(postRequestDto.getErrorMessage())
76+
.environment(postRequestDto.getEnvironment())
77+
.reproduceCode(postRequestDto.getReproduceCode())
78+
.solutionCode(postRequestDto.getSolutionCode())
79+
.causeAnalysis(postRequestDto.getCauseAnalysis())
80+
.referenceLink(postRequestDto.getReferenceLink())
81+
.extraContent(postRequestDto.getExtraContent())
82+
.createdAt(LocalDateTime.now())
83+
.editedAt(LocalDateTime.now())
84+
.postTags(new ArrayList<>())
85+
.build();
8286

8387
// 태그 저장
84-
List<Long> tagIds = postRequestDto.getTags(); // 이제 Long ID 목록임
85-
for (Long tagId : tagIds) {
86-
Tag tag = tagRepository.findById(tagId)
87-
.orElseThrow(() -> new CustomException(ErrorCode.TAG_NOT_FOUND));
88+
for (Tag tag : tags) {
8889
PostTag postTag = new PostTag(newPost, tag);
8990
newPost.getPostTags().add(postTag);
9091
}
91-
9292
postRepository.save(newPost);
9393
}
9494

95+
// 태그 다 선택 했는지
96+
private List<Tag> fetchAndValidateTags(List<Long> tagIds){
97+
// 태그 ID로 Tag 엔티티 조회
98+
List<Tag> tags = tagIds.stream()
99+
.map(tagId -> tagRepository.findById(tagId)
100+
.orElseThrow(() -> new CustomException(ErrorCode.TAG_NOT_FOUND)))
101+
.toList();
102+
103+
// 태그 종류별로 그룹화
104+
Map<TagCategory, List<Tag>> tagCategoryMap = tags.stream()
105+
.collect(Collectors.groupingBy(Tag::getTagCategory));
106+
107+
TagCategory[] requiredTypes = TagCategory.values();
108+
List<String> issues = new ArrayList<>();
109+
110+
// 하나라도 빠졌다면 예외 처리
111+
for (TagCategory type : requiredTypes){
112+
List<Tag> categories = tagCategoryMap.get(type);
113+
114+
if (type == TagCategory.MINOR_CATEGORY){ // 소분류는 4개까지 선택 가능
115+
if (categories == null)
116+
issues.add(type.name() + "태그가 선택되지 않았습니다.");
117+
else if (categories.size() > 4)
118+
issues.add(type.name() + "태그는 최대 4개까지 선택 가능합니다.");
119+
120+
} else {
121+
if (categories == null)
122+
issues.add(type.name() + "태그가 선택되지 않았습니다.");
123+
else if (categories.size() > 1)
124+
issues.add(type.name() + "태그는 하나만 선택해야 합니다.");
125+
}
126+
}
127+
128+
if (!issues.isEmpty()) {
129+
throw new CustomException(ErrorCode.REQUIRED_TAGS_MISSING);
130+
// throw new CustomException(ErrorCode.REQUIRED_TAGS_MISSING, String.join(", ", issues));
131+
// throw new CustomException(ErrorCode.REQUIRED_TAGS_MISSING.withDetail(missingTypes.toString()));
132+
}
133+
return tags;
134+
}
135+
136+
// 게시글 필수 항목 다 작성했는지
137+
private void validatePost(PostRequestDto postRequestDto){
138+
if (postRequestDto.getPostTitle().isBlank() | postRequestDto.getProblem().isBlank()
139+
| postRequestDto.getErrorMessage().isBlank() | postRequestDto.getEnvironment().isBlank()
140+
| postRequestDto.getReproduceCode().isBlank() | postRequestDto.getSolutionCode().isBlank())
141+
throw new CustomException(ErrorCode.REQUIRED_CONTENT_MISSING);
142+
}
143+
95144
// 게시글 조회하기
96145
public PostResponseDto viewPost(Long postId){
97146
Member member = memberService.getCurrentMemberInfo();
@@ -112,7 +161,7 @@ public PostResponseDto viewPost(Long postId){
112161
currentPost.getExtraContent(),
113162
currentPost.getPostTags().stream()
114163
.map(postTag -> postTag.getTagId().getTagName())
115-
.collect(Collectors.toList())
164+
.collect(toList())
116165
);
117166

118167
String nickname = member.getNickname();

0 commit comments

Comments
 (0)