Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT] 수정된 주제, 선택지 조회 API 반영 #53

Merged
merged 8 commits into from
Jul 24, 2024
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
package ddangkong.controller.balance.content.dto;

import ddangkong.controller.balance.option.dto.BalanceOptionResponse;
import ddangkong.domain.balance.content.BalanceContent;
import ddangkong.domain.balance.content.Category;
import ddangkong.domain.balance.content.RoomContent;
import ddangkong.domain.balance.option.BalanceOption;
import lombok.Builder;

public record BalanceContentResponse(
Long contentId,
Category category,
int totalRound,
int currentRound,
String question,
BalanceOptionResponse firstOption,
BalanceOptionResponse secondOption
) {

@Builder
private BalanceContentResponse(BalanceContent balanceContent,
private BalanceContentResponse(RoomContent roomContent,
BalanceOption firstOption,
BalanceOption secondOption) {
this(balanceContent.getId(),
balanceContent.getCategory(),
balanceContent.getName(),
this(roomContent.getContentId(),
roomContent.getContentCategory(),
roomContent.getTotalRound(),
roomContent.getRound(),
roomContent.getContentName(),
BalanceOptionResponse.from(firstOption),
BalanceOptionResponse.from(secondOption));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package ddangkong.controller.exception;

import ddangkong.service.excpetion.BusinessLogicException;
import ddangkong.service.excpetion.ViolateDataException;
import ddangkong.exception.BadRequestException;
import ddangkong.exception.InternalServerException;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
Expand Down Expand Up @@ -34,15 +34,15 @@ public ErrorResponse handleConstraintViolationException(ConstraintViolationExcep

@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleBusinessLogicException(BusinessLogicException e) {
public ErrorResponse handleBadRequestException(BadRequestException e) {
log.warn(e.getMessage());

return new ErrorResponse(e.getMessage());
}

@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleViolateDataException(ViolateDataException e) {
public ErrorResponse handleInternalServerErrorException(InternalServerException e) {
log.error(e.getMessage(), e);

return new ErrorResponse(SERVER_ERROR_MESSAGE);
Expand Down
10 changes: 10 additions & 0 deletions backend/src/main/java/ddangkong/domain/balance/content/Room.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package ddangkong.domain.balance.content;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
Expand All @@ -13,7 +14,16 @@
@Getter
public class Room {

private static final int DEFAULT_TOTAL_ROUND = 5;
private static final int DEFAULT_CURRENT_ROUND = 1;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false)
private int totalRound = DEFAULT_TOTAL_ROUND;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사소한 의견) default 값이지만 필드 주입보다는 생성자에서 넣는 것은 어떠신지요..!
곧 바뀔 거긴 한데 불..편합니다.. 못참겠어요ㅋㅋㅋㅋㅋ
사실 바꿀거면 지금이 눈에 잘띄어서 괜찮을 것 같기도 해서 사소한 의견으로 남겨봅니당ㅎㅎ

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

나중에 Room 생성 기능 구현 때에 추가하는 것이 좋을 것 같습니다! 이번에는 넘기도록 하겠습니다~


@Column(nullable = false)
private int currentRound = DEFAULT_CURRENT_ROUND;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ddangkong.domain.balance.content;

import ddangkong.domain.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
Expand Down Expand Up @@ -28,4 +29,23 @@ public class RoomContent extends BaseEntity {
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "balance_content_id")
private BalanceContent balanceContent;

@Column(nullable = false)
private int round;

public Long getContentId() {
return balanceContent.getId();
}

public Category getContentCategory() {
return balanceContent.getCategory();
}

public String getContentName() {
return balanceContent.getName();
}

public int getTotalRound() {
return room.getTotalRound();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@

public interface RoomContentRepository extends JpaRepository<RoomContent, Long> {

Optional<RoomContent> findTopByRoomIdOrderByCreatedAtDesc(Long roomId);
Optional<RoomContent> findByRoomAndRound(Room room, int round);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package ddangkong.domain.balance.content;

import org.springframework.data.jpa.repository.JpaRepository;

public interface RoomRepository extends JpaRepository<Room, Long> {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package ddangkong.exception;

public class BadRequestException extends RuntimeException {

public BadRequestException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package ddangkong.exception;

public class InternalServerException extends RuntimeException {

public InternalServerException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@

import ddangkong.controller.balance.content.dto.BalanceContentResponse;
import ddangkong.domain.balance.content.BalanceContent;
import ddangkong.domain.balance.content.Room;
import ddangkong.domain.balance.content.RoomContent;
import ddangkong.domain.balance.content.RoomContentRepository;
import ddangkong.domain.balance.content.RoomRepository;
import ddangkong.domain.balance.option.BalanceOption;
import ddangkong.domain.balance.option.BalanceOptionRepository;
import ddangkong.service.excpetion.BusinessLogicException;
import ddangkong.service.excpetion.ViolateDataException;
import ddangkong.exception.BadRequestException;
import ddangkong.exception.InternalServerException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
Expand All @@ -18,26 +21,29 @@ public class BalanceContentService {

private static final int BALANCE_OPTION_SIZE = 2;

private final RoomRepository roomRepository;

private final RoomContentRepository roomContentRepository;

private final BalanceOptionRepository balanceOptionRepository;

@Transactional(readOnly = true)
public BalanceContentResponse findRecentBalanceContent(Long roomId) {
BalanceContent balanceContent = findRecentContent(roomId);
List<BalanceOption> balanceOptions = findBalanceOptions(balanceContent);
RoomContent roomContent = findCurrentRoomContent(roomId);
List<BalanceOption> balanceOptions = findBalanceOptions(roomContent.getBalanceContent());

return BalanceContentResponse.builder()
.balanceContent(balanceContent)
.roomContent(roomContent)
.firstOption(balanceOptions.get(0))
.secondOption(balanceOptions.get(1))
.build();
}

private BalanceContent findRecentContent(Long roomId) {
return roomContentRepository.findTopByRoomIdOrderByCreatedAtDesc(roomId)
.orElseThrow(() -> new BusinessLogicException("해당 방의 질문이 존재하지 않습니다."))
.getBalanceContent();
private RoomContent findCurrentRoomContent(Long roomId) {
Room room = roomRepository.findById(roomId)
.orElseThrow(() -> new BadRequestException("해당 방이 존재하지 않습니다."));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사소한 의견) 이후에 중복 로직이 될 것 같아서 Repository에서 getById로 만들어두는 것은 어떨까 싶습니다:)
그리고 몇 번 roomId가 없는지 같이 에러 메시지 만들어주면 좋을 것 같아요! roomId 정보는 클라에게 노출해도 괜찮은 부분이지 않을까 싶습니다

return roomContentRepository.findByRoomAndRound(room, room.getCurrentRound())
.orElseThrow(() -> new BadRequestException("해당 방의 현재 진행중인 질문이 존재하지 않습니다."));
}

private List<BalanceOption> findBalanceOptions(BalanceContent balanceContent) {
Expand All @@ -48,7 +54,7 @@ private List<BalanceOption> findBalanceOptions(BalanceContent balanceContent) {

private void validateBalanceOptions(List<BalanceOption> balanceOptions) {
if (balanceOptions.size() != BALANCE_OPTION_SIZE) {
throw new ViolateDataException("밸런스 게임의 선택지가 %d개입니다".formatted(balanceOptions.size()));
throw new InternalServerException("밸런스 게임의 선택지가 %d개입니다".formatted(balanceOptions.size()));
}
}
}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class BalanceContentControllerTest extends BaseControllerTest {
class 현재_방의_내용_조회 {

private static final BalanceContentResponse EXPECTED_RESPONSE = new BalanceContentResponse(
1L, Category.EXAMPLE, "민초 vs 반민초",
1L, Category.EXAMPLE, 5, 2, "민초 vs 반민초",
new BalanceOptionResponse(1L, "민초"),
new BalanceOptionResponse(2L, "반민초"));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,21 @@ class RoomContentRepositoryTest extends BaseRepositoryTest {
@Autowired
private RoomContentRepository roomContentRepository;

@Autowired
private RoomRepository roomRepository;

@Nested
class 방의_최신_질문_조회 {
class 방의_해당_라운드_질문_조회 {

@Test
void 방의_가장_최신의_질문을_조회할_수_있다() {
void 방의_해당_라운드의_질문을_조회할_수_있다() {
// given
Long roomId = 1L;
Room room = roomRepository.findById(roomId).get();
int round = 2;

// when
RoomContent actual = roomContentRepository.findTopByRoomIdOrderByCreatedAtDesc(roomId).get();
RoomContent actual = roomContentRepository.findByRoomAndRound(room, round).get();

// then
assertThat(actual.getId()).isEqualTo(2L);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,29 @@
import ddangkong.controller.balance.content.dto.BalanceContentResponse;
import ddangkong.controller.balance.option.dto.BalanceOptionResponse;
import ddangkong.domain.balance.content.Category;
import ddangkong.exception.BadRequestException;
import ddangkong.service.BaseServiceTest;
import ddangkong.service.excpetion.BusinessLogicException;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

class BalanceContentServiceTest extends BaseServiceTest {

private static final Long PROGRESS_ROOM_ID = 1L;
private static final Long NOT_EXIST_ROOM_ID = 2L;
private static final BalanceContentResponse BALANCE_CONTENT_RESPONSE = new BalanceContentResponse(
1L, Category.EXAMPLE, "민초 vs 반민초",
new BalanceOptionResponse(1L, "민초"),
new BalanceOptionResponse(2L, "반민초"));

@Autowired
private BalanceContentService balanceContentService;

@Nested
class 현재_방의_밸런스_게임_내용_조회 {

private static final Long PROGRESS_ROOM_ID = 1L;
private static final Long NOT_EXIST_ROOM_ID = 3L;
private static final Long NOT_PROGRESSED_ROOM_ID = 2L;
private static final BalanceContentResponse BALANCE_CONTENT_RESPONSE = new BalanceContentResponse(
1L, Category.EXAMPLE, 5, 2, "민초 vs 반민초",
new BalanceOptionResponse(1L, "민초"),
new BalanceOptionResponse(2L, "반민초"));

@Test
void 방의_최신_밸런스_게임_내용을_조회할_수_있다() {
void 방의_진행_중인_밸런스_게임_내용을_조회할_수_있다() {
// when
BalanceContentResponse actual = balanceContentService.findRecentBalanceContent(PROGRESS_ROOM_ID);

Expand All @@ -40,8 +40,16 @@ class 현재_방의_밸런스_게임_내용_조회 {
void 방이_없을_경우_예외를_던진다() {
// when & then
assertThatThrownBy(() -> balanceContentService.findRecentBalanceContent(NOT_EXIST_ROOM_ID))
.isInstanceOf(BusinessLogicException.class)
.hasMessage("해당 방의 질문이 존재하지 않습니다.");
.isInstanceOf(BadRequestException.class)
.hasMessage("해당 방이 존재하지 않습니다.");
}

@Test
void 방의_현재_라운드의_질문이_없을_경우_예외를_던진다() {
// when & then
assertThatThrownBy(() -> balanceContentService.findRecentBalanceContent(NOT_PROGRESSED_ROOM_ID))
.isInstanceOf(BadRequestException.class)
.hasMessage("해당 방의 현재 진행중인 질문이 존재하지 않습니다.");
}
}
}
10 changes: 5 additions & 5 deletions backend/src/test/resources/init-test.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
INSERT INTO room ()
VALUES ();
INSERT INTO room (total_round, current_round)
VALUES (5, 2), (5, 1);

INSERT INTO member (nickname, room_id)
VALUES ('mohamedeu al katan', 1),
Expand All @@ -11,9 +11,9 @@ INSERT INTO balance_content (category, name)
VALUES ('EXAMPLE', '민초 vs 반민초'),
('EXAMPLE', '월 200 백수 vs 월 500 직장인');

INSERT INTO room_content (room_id, balance_content_id, created_at)
VALUES (1, 2, '2024-07-18 19:50:00.000'),
(1, 1, '2024-07-18 20:00:00.000');
INSERT INTO room_content (room_id, balance_content_id, round, created_at)
VALUES (1, 2, 1, '2024-07-18 19:50:00.000'),
(1, 1, 2, '2024-07-18 20:00:00.000');

INSERT INTO balance_option (name, balance_content_id)
VALUES ('민초', 1),
Expand Down