Skip to content

Commit

Permalink
태그가 중복 저장되는 버그 해결 (#922)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyum-q authored Nov 18, 2024
2 parents 0b4fcda + 664ea0d commit cb61c8e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 14 deletions.
39 changes: 25 additions & 14 deletions backend/src/main/java/codezap/tag/service/TagService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package codezap.tag.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
Expand All @@ -25,22 +24,34 @@ public class TagService {

@Transactional
public void createTags(Template template, List<String> tagNames) {
List<Tag> existingTags = new ArrayList<>(tagRepository.findAllByNames(tagNames));
List<String> existNames = existingTags.stream()
List<Tag> existTags = tagRepository.findAllByNames(tagNames);
List<String> existNames = getExistTagNames(existTags);

List<Tag> newTags = getOnlyNewTags(existNames, tagNames);
List<Tag> savedNewTags = tagRepository.saveAll(newTags);
existTags.addAll(savedNewTags);
saveTemplateTags(template, existTags);
}

private List<String> getExistTagNames(List<Tag> existTags) {
return existTags.stream()
.map(Tag::getName)
.toList();
}

private List<Tag> getOnlyNewTags(List<String> existNames, List<String> tagNames) {
return tagNames.stream()
.distinct()
.filter(name -> !existNames.contains(name))
.map(Tag::new)
.toList();
}

List<Tag> newTags = tagRepository.saveAll(
tagNames.stream()
.filter(name -> !existNames.contains(name))
.map(Tag::new)
.toList()
);
existingTags.addAll(newTags);

for (Tag existingTag : existingTags) {
templateTagRepository.save(new TemplateTag(template, existingTag));
}
private void saveTemplateTags(Template template, List<Tag> tags) {
List<TemplateTag> templateTags = tags.stream()
.map(tag -> new TemplateTag(template, tag))
.toList();
templateTagRepository.saveAll(templateTags);
}

public List<Tag> findAllByTemplate(Template template) {
Expand Down
17 changes: 17 additions & 0 deletions backend/src/test/java/codezap/tag/service/TagServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,23 @@ void createTags_WhenExistTemplateTagContains() {
.containsExactlyElementsOf(tagNames);
}

@Test
@DisplayName("성공: 저장하려는 태그에 중복이 있는 경우 하나만 생성")
void createTags_WhenDuplicatedTemplateTag() {
// given
Template template = createSavedTemplate();
String tagName = "tag1";
List<String> tagNames = Arrays.asList(tagName, tagName);

// when
sut.createTags(template, tagNames);

// then
List<String> savedTemplateTagNames = getSavedTemplateTagNames(template);
assertThat(savedTemplateTagNames).hasSize(1)
.containsExactly(tagName);
}

@Test
@DisplayName("성공: 이미 있는 태그이지만 이 템플릿의 태그가 아닌 경우 템플릿 태그만 추가")
void createTags_WhenExistTagContains() {
Expand Down

0 comments on commit cb61c8e

Please sign in to comment.