|
| 1 | +package com.cona.KUsukKusuk.bookmark.service; |
| 2 | + |
| 3 | +import com.cona.KUsukKusuk.bookmark.domain.Bookmark; |
| 4 | +import com.cona.KUsukKusuk.bookmark.dto.BookmarkResponseDto; |
| 5 | +import com.cona.KUsukKusuk.bookmark.dto.UserBookmarkResponse; |
| 6 | +import com.cona.KUsukKusuk.bookmark.exception.BookmarkException; |
| 7 | +import com.cona.KUsukKusuk.bookmark.repository.BookmarkRepository; |
| 8 | +import com.cona.KUsukKusuk.global.exception.HttpExceptionCode; |
| 9 | +import com.cona.KUsukKusuk.spot.domain.Spot; |
| 10 | +import com.cona.KUsukKusuk.spot.exception.SpotNotFoundException; |
| 11 | +import com.cona.KUsukKusuk.spot.repository.SpotRepository; |
| 12 | +import com.cona.KUsukKusuk.user.domain.User; |
| 13 | +import com.cona.KUsukKusuk.user.service.UserService; |
| 14 | +import java.util.List; |
| 15 | +import java.util.stream.Collectors; |
| 16 | +import lombok.RequiredArgsConstructor; |
| 17 | +import org.springframework.stereotype.Service; |
| 18 | + |
| 19 | +@Service |
| 20 | +@RequiredArgsConstructor |
| 21 | +public class BookmarkService { |
| 22 | + private final BookmarkRepository bookmarkRepository; |
| 23 | + private final UserService userService; |
| 24 | + private final SpotRepository spotRepository; |
| 25 | + |
| 26 | + public void addBookmark(Long spotId) { |
| 27 | + String username = userService.getUsernameBySecurityContext(); |
| 28 | + User user = userService.findUserByUserid(username); |
| 29 | + |
| 30 | + Spot spot = spotRepository.findById(spotId) |
| 31 | + .orElseThrow(() -> new SpotNotFoundException(HttpExceptionCode.SPOT_NOT_FOUND)); |
| 32 | + |
| 33 | + Bookmark bookmark = new Bookmark(); |
| 34 | + bookmark.setUser(user); |
| 35 | + bookmark.setSpot(spot); |
| 36 | + |
| 37 | + bookmarkRepository.save(bookmark); |
| 38 | + } |
| 39 | + |
| 40 | + public void deleteBookmark(Long bookmarkId) { |
| 41 | + bookmarkRepository.deleteById(bookmarkId); |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + public List<BookmarkResponseDto> getUserBookmarks() { |
| 46 | + String username = userService.getUsernameBySecurityContext(); |
| 47 | + User user = userService.findUserByUserid(username); |
| 48 | + List<Bookmark> userBookmarks = bookmarkRepository.findByUser(user); |
| 49 | + if (userBookmarks == null || userBookmarks.isEmpty()) { |
| 50 | + throw new BookmarkException(HttpExceptionCode.BOOK_MARK_NOT_EXIST); |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + return userBookmarks.stream() |
| 55 | + .map(bookmark -> BookmarkResponseDto.of(bookmark,bookmark.getSpot())) |
| 56 | + .collect(Collectors.toList()); |
| 57 | + } |
| 58 | +} |
0 commit comments