diff --git a/backend/src/main/java/codezap/tag/service/TagService.java b/backend/src/main/java/codezap/tag/service/TagService.java index a1156f5fb..0222be680 100644 --- a/backend/src/main/java/codezap/tag/service/TagService.java +++ b/backend/src/main/java/codezap/tag/service/TagService.java @@ -1,6 +1,5 @@ package codezap.tag.service; -import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; @@ -25,22 +24,34 @@ public class TagService { @Transactional public void createTags(Template template, List tagNames) { - List existingTags = new ArrayList<>(tagRepository.findAllByNames(tagNames)); - List existNames = existingTags.stream() + List existTags = tagRepository.findAllByNames(tagNames); + List existNames = getExistTagNames(existTags); + + List newTags = getOnlyNewTags(existNames, tagNames); + List savedNewTags = tagRepository.saveAll(newTags); + existTags.addAll(savedNewTags); + saveTemplateTags(template, existTags); + } + + private List getExistTagNames(List existTags) { + return existTags.stream() .map(Tag::getName) .toList(); + } + + private List getOnlyNewTags(List existNames, List tagNames) { + return tagNames.stream() + .distinct() + .filter(name -> !existNames.contains(name)) + .map(Tag::new) + .toList(); + } - List 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 tags) { + List templateTags = tags.stream() + .map(tag -> new TemplateTag(template, tag)) + .toList(); + templateTagRepository.saveAll(templateTags); } public List findAllByTemplate(Template template) { diff --git a/backend/src/test/java/codezap/tag/service/TagServiceTest.java b/backend/src/test/java/codezap/tag/service/TagServiceTest.java index 5c12fc2b9..e4589eb7c 100644 --- a/backend/src/test/java/codezap/tag/service/TagServiceTest.java +++ b/backend/src/test/java/codezap/tag/service/TagServiceTest.java @@ -68,6 +68,23 @@ void createTags_WhenExistTemplateTagContains() { .containsExactlyElementsOf(tagNames); } + @Test + @DisplayName("성공: 저장하려는 태그에 중복이 있는 경우 하나만 생성") + void createTags_WhenDuplicatedTemplateTag() { + // given + Template template = createSavedTemplate(); + String tagName = "tag1"; + List tagNames = Arrays.asList(tagName, tagName); + + // when + sut.createTags(template, tagNames); + + // then + List savedTemplateTagNames = getSavedTemplateTagNames(template); + assertThat(savedTemplateTagNames).hasSize(1) + .containsExactly(tagName); + } + @Test @DisplayName("성공: 이미 있는 태그이지만 이 템플릿의 태그가 아닌 경우 템플릿 태그만 추가") void createTags_WhenExistTagContains() {