Skip to content

Commit

Permalink
[FEAT] 북마크 컨트롤러 구현 및 TransportType Enum 리팩토링 (#86)
Browse files Browse the repository at this point in the history
- 북마크 컨트롤러 구현
  - `GET` `/bookmark` : 본인이 작성한 북마크 리스트 반환
  - `GET` `/bookmark/{bookmarkId}` : bookmarkId로 북마크 조회
  - `POST` `/bookmark` : 북마크 생성
  - `DELETE` `/bookmark/{bookmarkId}` : bookmarkId로 북마크 삭제
  -  `PUT` `/bookmark/{bookmarkId}` : bookmarkId로 북마크 수정

- 북마크 서비스 수정
  - `getBookmarkById` 메소드에서 본인이 작성한 북마크만 조회하도록 수정 
  - 북마크 서비스 메소드 순서 변경 : get, create, update, delete 순서
  - 메소드 파라미터 순서 수정 : dto, userId, bookmarkId 순서
- 받아야하는 파라미터가 늘어날수록 코드 가독성이 나빠질 수 있음 -> 추후 service단에서 사용할 dto를 분리하도록
리팩토링 고려

- TransportType Enum 리팩토링
- `BookmarkRespDto` 에서 `TransportType`를 `String`이 아닌 `enum`으로 반환하도록 리팩토링
  - `TransportType`에서 `name` 필드가 불필요하다고 생각되어 삭제

close #84
  • Loading branch information
Gyaak authored Aug 18, 2024
1 parent 86d054f commit f042173
Show file tree
Hide file tree
Showing 4 changed files with 130 additions and 23 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package com.talkka.server.bookmark.controller;

import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.talkka.server.bookmark.dto.BookmarkReqDto;
import com.talkka.server.bookmark.dto.BookmarkRespDto;
import com.talkka.server.bookmark.exception.BookmarkNotFoundException;
import com.talkka.server.bookmark.exception.BookmarkUserNotFoundException;
import com.talkka.server.bookmark.exception.enums.InvalidTransportTypeEnumException;
import com.talkka.server.bookmark.service.BookmarkService;
import com.talkka.server.oauth.domain.OAuth2UserInfo;
import com.talkka.server.review.exception.ContentAccessException;

import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
@RequestMapping("/bookmark")
public class BookmarkController {
private final BookmarkService bookmarkService;

// 본인이 작성한 북마크 리스트만 조회
@GetMapping("")
public ResponseEntity<?> getBookmarkList(@AuthenticationPrincipal OAuth2UserInfo oAuth2UserInfo) {
List<BookmarkRespDto> bookmarks = bookmarkService.getBookmarkByUserId(oAuth2UserInfo.getUserId());
return ResponseEntity.ok(bookmarks);
}

@GetMapping("/{bookmarkId}")
public ResponseEntity<?> getBookmark(@AuthenticationPrincipal OAuth2UserInfo oAuth2UserInfo,
@PathVariable Long bookmarkId) {
ResponseEntity<?> response;
try {
BookmarkRespDto bookmark = bookmarkService.getBookmarkById(oAuth2UserInfo.getUserId(), bookmarkId);
response = ResponseEntity.ok(bookmark);
} catch (BookmarkNotFoundException | BookmarkUserNotFoundException exception) {
response = ResponseEntity.badRequest().body(exception.getMessage());
} catch (ContentAccessException exception) {
response = ResponseEntity.status(HttpStatus.FORBIDDEN).body(exception.getMessage());
}
return response;
}

@PostMapping("")
public ResponseEntity<?> createBookmark(@AuthenticationPrincipal OAuth2UserInfo oAuth2UserInfo,
BookmarkReqDto bookmarkReqDto) {
ResponseEntity<?> response;
try {
BookmarkRespDto bookmark = bookmarkService.createBookmark(bookmarkReqDto, oAuth2UserInfo.getUserId());
return ResponseEntity.ok(bookmark);
} catch (BookmarkUserNotFoundException | InvalidTransportTypeEnumException exception) {
response = ResponseEntity.badRequest().body(exception.getMessage());
}
return response;
}

@PutMapping("{bookmarkId}")
public ResponseEntity<?> updateBookmark(@AuthenticationPrincipal OAuth2UserInfo oAuth2UserInfo,
BookmarkReqDto bookmarkReqDto, @PathVariable Long bookmarkId) {
ResponseEntity<?> response;
try {
BookmarkRespDto bookmark = bookmarkService.updateBookmark(bookmarkReqDto, oAuth2UserInfo.getUserId(),
bookmarkId);
response = ResponseEntity.ok(bookmark);
} catch (BookmarkNotFoundException | BookmarkUserNotFoundException
| InvalidTransportTypeEnumException exception) {
response = ResponseEntity.badRequest().body(exception.getMessage());
} catch (ContentAccessException exception) {
response = ResponseEntity.status(HttpStatus.FORBIDDEN).body(exception.getMessage());
}
return response;
}

@DeleteMapping("/{bookmarkId}")
public ResponseEntity<?> deleteBookmark(@AuthenticationPrincipal OAuth2UserInfo oAuth2UserInfo,
@PathVariable Long bookmarkId) {
ResponseEntity<?> response;
try {
bookmarkService.deleteBookmark(oAuth2UserInfo.getUserId(), bookmarkId);
response = ResponseEntity.ok().build();
} catch (BookmarkNotFoundException | BookmarkUserNotFoundException exception) {
response = ResponseEntity.badRequest().body(exception.getMessage());
} catch (ContentAccessException exception) {
response = ResponseEntity.status(HttpStatus.FORBIDDEN).body(exception.getMessage());
}
return response;
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
package com.talkka.server.bookmark.dto;

import com.talkka.server.bookmark.dao.BookmarkDetailEntity;
import com.talkka.server.bookmark.enums.TransportType;
import com.talkka.server.subway.enums.Updown;

public record BookmarkDetailRespDto(
Integer seq,
String type,
TransportType type,
Long subwayStationId,
Updown subwayUpdown,
Long busRouteStationId
) {
public static BookmarkDetailRespDto of(BookmarkDetailEntity entity) {
return new BookmarkDetailRespDto(
entity.getSeq(),
entity.getType().getType(),
entity.getType(),
entity.getSubwayStationId(),
entity.getSubwayUpdown(),
entity.getBusRouteStationId()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,9 @@

@Getter
public enum TransportType {
BUS("bus"), SUBWAY("subway");
BUS, SUBWAY;

private final String type;

TransportType(String type) {
this.type = type;
TransportType() {
}

public static TransportType valueOfEnumString(String enumValue) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.talkka.server.bookmark.dto.BookmarkRespDto;
import com.talkka.server.bookmark.exception.BookmarkNotFoundException;
import com.talkka.server.bookmark.exception.BookmarkUserNotFoundException;
import com.talkka.server.bookmark.exception.enums.InvalidTransportTypeEnumException;
import com.talkka.server.common.validator.ContentAccessValidator;
import com.talkka.server.review.exception.ContentAccessException;
import com.talkka.server.user.dao.UserEntity;
Expand All @@ -27,39 +28,48 @@ public class BookmarkService {
private final UserRepository userRepository;
private final ContentAccessValidator contentAccessValidator;

@Transactional
public BookmarkRespDto createBookmark(BookmarkReqDto dto, Long userId) throws BookmarkUserNotFoundException {
public BookmarkRespDto getBookmarkById(Long userId, Long bookmarkId) throws
BookmarkNotFoundException,
BookmarkUserNotFoundException,
ContentAccessException {
// 본인이 작성한 북마크만 조회 하도록 변경
UserEntity user = userRepository.findById(userId).orElseThrow(BookmarkUserNotFoundException::new);
BookmarkEntity bookmark = dto.toEntity(user);
dto.details().stream()
.map(detail -> detail.toEntity(bookmark))
.forEach(bookmark.getDetails()::add);
return BookmarkRespDto.of(bookmarkRepository.save(bookmark));
}

public BookmarkRespDto getByBookmarkId(Long id) throws BookmarkNotFoundException {
BookmarkEntity bookmark = bookmarkRepository.findById(id).orElseThrow(BookmarkUserNotFoundException::new);
BookmarkEntity bookmark = bookmarkRepository.findById(bookmarkId)
.orElseThrow(BookmarkUserNotFoundException::new);
contentAccessValidator.validateOwnerContentAccess(userId, user.getGrade(), bookmark.getUser().getId());
return BookmarkRespDto.of(bookmark);
}

public List<BookmarkRespDto> getByUserId(Long userId) {
public List<BookmarkRespDto> getBookmarkByUserId(Long userId) {
return bookmarkRepository.findByUserId(userId).stream()
.map(BookmarkRespDto::of)
.toList();
}

@Transactional
public BookmarkRespDto updateBookmark(BookmarkReqDto dto, Long bookmarkId, Long userId) throws
public BookmarkRespDto createBookmark(BookmarkReqDto dto, Long userId) throws BookmarkUserNotFoundException,
InvalidTransportTypeEnumException {
UserEntity user = userRepository.findById(userId).orElseThrow(BookmarkUserNotFoundException::new);
BookmarkEntity bookmark = dto.toEntity(user);
dto.details().stream()
.map(detail -> detail.toEntity(bookmark))
.forEach(bookmark.getDetails()::add);
return BookmarkRespDto.of(bookmarkRepository.save(bookmark));
}

@Transactional
public BookmarkRespDto updateBookmark(BookmarkReqDto dto, Long userId, Long bookmarkId) throws
BookmarkUserNotFoundException,
BookmarkNotFoundException,
InvalidTransportTypeEnumException,
ContentAccessException {

UserEntity user = userRepository.findById(userId).orElseThrow(BookmarkUserNotFoundException::new);
BookmarkEntity bookmark = bookmarkRepository.findById(bookmarkId)
.orElseThrow(BookmarkUserNotFoundException::new);
.orElseThrow(BookmarkNotFoundException::new);

// 작성자거나 관리자가 아니면 ContentAccessException 발생
contentAccessValidator.validateOwnerContentAccess(user.getId(), user.getGrade(), bookmark.getId());
contentAccessValidator.validateOwnerContentAccess(user.getId(), user.getGrade(), bookmark.getUser().getId());

// 기존 북마크 상세를 전부 지우고 전체를 새로 저장함
bookmarkDetailRepository.deleteByBookmarkId(bookmarkId);
Expand All @@ -69,7 +79,7 @@ public BookmarkRespDto updateBookmark(BookmarkReqDto dto, Long bookmarkId, Long
}

@Transactional
public Long deleteBookmark(Long bookmarkId, Long userId) throws
public Long deleteBookmark(Long userId, Long bookmarkId) throws
BookmarkUserNotFoundException,
BookmarkNotFoundException {

Expand Down

0 comments on commit f042173

Please sign in to comment.