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: 방 입장 기능 구현 #30

Merged
merged 1 commit into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/docs/asciidoc/api/room.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,31 @@ include::{snippets}/fetch-room-list-success/http-request.adoc[]

include::{snippets}/fetch-room-list-success/http-response.adoc[]
include::{snippets}/fetch-room-list-success/response-fields.adoc[]

{nbsp}

[[enter-room-success]]
=== 방 입장 성공

==== HTTP Request

include::{snippets}/enter-room-success/http-request.adoc[]

==== HTTP Response

include::{snippets}/enter-room-success/http-response.adoc[]
include::{snippets}/enter-room-success/response-fields.adoc[]

{nbsp}

[[enter-room-fail-single-room-participant-violation]]
=== 방 입장 실패: 다수의 방에 참가할 수 없습니다

==== HTTP Request

include::{snippets}/enter-room-fail-single-room-participant-violation/http-request.adoc[]

==== HTTP Response

include::{snippets}/enter-room-fail-single-room-participant-violation/http-response.adoc[]
include::{snippets}/enter-room-fail-single-room-participant-violation/response-fields.adoc[]
1 change: 1 addition & 0 deletions src/main/java/site/youtogether/exception/ErrorType.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public enum ErrorType {
COOKIE_INVALID(HttpStatus.BAD_REQUEST, "입력으로 들어온 세션 쿠키값과 대응되는 유저 아이디가 없습니다"),

// Room
ROOM_NO_EXISTENCE(HttpStatus.NOT_FOUND, "방이 없습니다"),
SINGLE_ROOM_PARTICIPATION_VIOLATION(HttpStatus.BAD_REQUEST, "하나의 방에만 참가할 수 있습니다");

private final HttpStatus status;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package site.youtogether.exception.room;

import site.youtogether.exception.CustomException;
import site.youtogether.exception.ErrorType;

public class RoomNoExistenceException extends CustomException {

public RoomNoExistenceException() {
super(ErrorType.ROOM_NO_EXISTENCE);
}

}
27 changes: 24 additions & 3 deletions src/main/java/site/youtogether/room/application/RoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
import org.springframework.stereotype.Service;

import lombok.RequiredArgsConstructor;
import site.youtogether.exception.room.RoomNoExistenceException;
import site.youtogether.room.Room;
import site.youtogether.room.dto.CreatedRoomInfo;
import site.youtogether.room.dto.RoomDetail;
import site.youtogether.room.dto.RoomList;
import site.youtogether.room.dto.RoomSettings;
import site.youtogether.room.infrastructure.RoomStorage;
Expand All @@ -26,7 +27,7 @@ public class RoomService {
private final UserStorage userStorage;
private final UserTrackingStorage userTrackingStorage;

public CreatedRoomInfo create(String cookieValue, RoomSettings roomSettings, LocalDateTime now) {
public RoomDetail create(String cookieValue, RoomSettings roomSettings, LocalDateTime now) {
Long userId = userTrackingStorage.save(cookieValue);

User host = User.builder()
Expand All @@ -46,12 +47,32 @@ public CreatedRoomInfo create(String cookieValue, RoomSettings roomSettings, Loc
userStorage.save(host);
roomStorage.save(room);

return new CreatedRoomInfo(room, host);
return new RoomDetail(room, host);
}

public RoomList fetchAll(Pageable pageable, String keyword) {
Slice<Room> roomSlice = roomStorage.findSliceBy(pageable, keyword);
return new RoomList(roomSlice);
}

public RoomDetail enter(String cookieValue, String roomCode) {
Long userId = userTrackingStorage.save(cookieValue);

User user = User.builder()
.userId(userId)
.nickname(RandomUtil.generateUserNickname())
.role(Role.GUEST)
.build();

Room room = roomStorage.findById(roomCode)
.orElseThrow(RoomNoExistenceException::new);

room.getParticipants().put(user.getUserId(), user);

userStorage.save(user);
roomStorage.save(room);

return new RoomDetail(room, room.getHost());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

@AllArgsConstructor
@Getter
public class CreatedRoomInfo {
public class RoomDetail {

private final String roomCode;
private final String roomTitle;
Expand All @@ -16,7 +16,7 @@ public class CreatedRoomInfo {
private final int currentParticipant;
private final boolean passwordExist;

public CreatedRoomInfo(Room room, User host) {
public RoomDetail(Room room, User host) {
this.roomCode = room.getCode();
this.roomTitle = room.getTitle();
this.hostNickname = host.getNickname();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
Expand All @@ -21,7 +22,7 @@
import lombok.RequiredArgsConstructor;
import site.youtogether.config.property.CookieProperties;
import site.youtogether.room.application.RoomService;
import site.youtogether.room.dto.CreatedRoomInfo;
import site.youtogether.room.dto.RoomDetail;
import site.youtogether.room.dto.RoomList;
import site.youtogether.room.dto.RoomSettings;
import site.youtogether.util.RandomUtil;
Expand All @@ -36,19 +37,19 @@ public class RoomController {
private final RoomService roomService;

@PostMapping("/rooms")
public ResponseEntity<ApiResponse<CreatedRoomInfo>> createRoom(@Valid @RequestBody RoomSettings roomSettings, HttpServletResponse response) {
public ResponseEntity<ApiResponse<RoomDetail>> createRoom(@Valid @RequestBody RoomSettings roomSettings, HttpServletResponse response) {
// Generate a new session code and set it as a cookie.
ResponseCookie cookie = generateSessionCookie();

// Create a new room with the generated session code.
CreatedRoomInfo createdRoomInfo = roomService.create(cookie.getValue(), roomSettings, LocalDateTime.now());
RoomDetail roomDetail = roomService.create(cookie.getValue(), roomSettings, LocalDateTime.now());

// Add the cookie to the response header.
response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());

// Return a response indicating successful room creation.
return ResponseEntity.status(HttpStatus.CREATED)
.body(ApiResponse.created(ResponseResult.ROOM_CREATION_SUCCESS, createdRoomInfo));
.body(ApiResponse.created(ResponseResult.ROOM_CREATION_SUCCESS, roomDetail));
}

@GetMapping("/rooms")
Expand All @@ -59,6 +60,18 @@ public ResponseEntity<ApiResponse<RoomList>> fetchRoomList(@PageableDefault Page
.body(ApiResponse.ok(ResponseResult.ROOM_LIST_FETCH_SUCCESS, roomList));
}

@PostMapping("/rooms/{roomCode}")
public ResponseEntity<ApiResponse<RoomDetail>> enterRoom(@PathVariable String roomCode, HttpServletResponse response) {
ResponseCookie cookie = generateSessionCookie();

RoomDetail roomDetail = roomService.enter(cookie.getValue(), roomCode);

response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());

return ResponseEntity.ok(
ApiResponse.ok(ResponseResult.ROOM_ENTER_SUCCESS, roomDetail));
}

private ResponseCookie generateSessionCookie() {
return ResponseCookie.from(cookieProperties.getName(), RandomUtil.generateRandomCode(COOKIE_VALUE_LENGTH))
.domain(cookieProperties.getDomain())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public enum ResponseResult {

// Room
ROOM_CREATION_SUCCESS("방 생성에 성공했습니다"),
ROOM_ENTER_SUCCESS("방 입장에 성공했습니다"),
ROOM_LIST_FETCH_SUCCESS("방 목록 조회에 성공했습니다");

private final String description;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

import site.youtogether.IntegrationTestSupport;
import site.youtogether.room.Room;
import site.youtogether.room.dto.CreatedRoomInfo;
import site.youtogether.room.dto.RoomDetail;
import site.youtogether.room.dto.RoomList;
import site.youtogether.room.dto.RoomSettings;
import site.youtogether.room.infrastructure.RoomStorage;
Expand Down Expand Up @@ -62,15 +62,15 @@ void createSuccess() {
.build();

// when
CreatedRoomInfo createdRoomInfo = roomService.create(cookieValue, roomSettings, LocalDateTime.now());
RoomDetail createdRoomDetail = roomService.create(cookieValue, roomSettings, LocalDateTime.now());

// then
Room room = roomStorage.findById(createdRoomInfo.getRoomCode()).get();
Room room = roomStorage.findById(createdRoomDetail.getRoomCode()).get();
Long userId = userTrackingStorage.findByCookieValue(cookieValue).get();
User user = userStorage.findById(userId).get();

assertThat(createdRoomInfo.getRoomCode()).hasSize(ROOM_CODE_LENGTH);
assertThat(createdRoomInfo.getRoomCode()).isEqualTo(room.getCode());
assertThat(createdRoomDetail.getRoomCode()).hasSize(ROOM_CODE_LENGTH);
assertThat(createdRoomDetail.getRoomCode()).isEqualTo(room.getCode());
assertThat(room.getCapacity()).isEqualTo(10);
assertThat(room.getTitle()).isEqualTo("재밌는 쇼츠 같이 보기");
assertThat(room.getPassword()).isNull();
Expand Down Expand Up @@ -119,6 +119,25 @@ void fetchRoomSlice() throws Exception {
assertThat(roomList3.isHasNext()).isFalse();
}

@Test
@DisplayName("방에 입장 한다")
void enterRoom() throws Exception {
// given
Room room = createRoom(LocalDateTime.of(2024, 4, 10, 11, 37, 0), "연똥땡의 방");
String cookieValue = "adljfkalskdfj";

// when
roomService.enter(cookieValue, room.getCode());

// then
Long userId = userTrackingStorage.findByCookieValue(cookieValue).get();
User enterUser = userStorage.findById(userId).get();
Room savedRoom = roomStorage.findById(room.getCode()).get();

assertThat(savedRoom.getParticipants()).containsKey(userId);
assertThat(savedRoom.getParticipants().get(userId)).usingRecursiveComparison().isEqualTo(enterUser);
}

private Room createRoom(LocalDateTime createTime, String title) {
User user = User.builder()
.userId(1L)
Expand Down
Loading
Loading