-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
35 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 34 additions & 1 deletion
35
src/main/java/com/developer/wiki/bookmark/BookmarkService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,38 @@ | ||
package com.developer.wiki.oauth.service; | ||
package com.developer.wiki.bookmark; | ||
|
||
import com.developer.wiki.common.exception.NotFoundException; | ||
import com.developer.wiki.oauth.UserRepository; | ||
import com.developer.wiki.question.command.domain.Question; | ||
import com.developer.wiki.question.command.domain.QuestionRepository; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.stereotype.Service; | ||
import org.springframework.transaction.annotation.Transactional; | ||
|
||
@Service | ||
@Transactional | ||
@RequiredArgsConstructor | ||
public class BookmarkService { | ||
|
||
private final QuestionRepository questionRepository; | ||
private final UserRepository userRepository; | ||
private final BookmarkRepository bookmarkRepository; | ||
|
||
public void toggle(Long questionId, Long userId) { | ||
Question question = questionRepository.findById(questionId) | ||
.orElseThrow(() -> new NotFoundException("존재하지 않는 ID입니다.")); | ||
bookmarkRepository.findByUserIdAndQuestion(userId, question).ifPresentOrElse(bookmark -> { | ||
unBookmark(bookmark); | ||
}, () -> { | ||
bookmark(userId, question); | ||
}); | ||
} | ||
|
||
private void bookmark(Long userId, Question question) { | ||
Bookmark bookmark = new Bookmark(userId, question); | ||
bookmarkRepository.save(bookmark); | ||
} | ||
|
||
private void unBookmark(Bookmark bookmark) { | ||
bookmarkRepository.delete(bookmark); | ||
} | ||
} |