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

release: 닉네임 중복 검사 API 배포 #91

Merged
merged 4 commits into from
May 18, 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/user.adoc
Original file line number Diff line number Diff line change
@@ -1,6 +1,34 @@
[[User-API]]
== User API

[[check-nickname-success]]
=== 닉네임 중복 검사 성공

==== HTTP Request

include::{snippets}/check-nickname-success/http-request.adoc[]

==== HTTP Response

include::{snippets}/check-nickname-success/http-response.adoc[]
include::{snippets}/check-nickname-success/response-fields.adoc[]

{nbsp}

[[check-nickname-fail]]
=== 닉네임 중복 검사 실패

==== HTTP Request

include::{snippets}/check-nickname-fail/http-request.adoc[]

==== HTTP Response

include::{snippets}/check-nickname-fail/http-response.adoc[]
include::{snippets}/check-nickname-fail/response-fields.adoc[]

{nbsp}

[[change-nickname-success]]
=== 닉네임 변경 성공

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/site/youtogether/playlist/PlayerState.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

public enum PlayerState {

PLAY, PAUSE, END, SKIP, RATE
PLAY, PAUSE, END, RATE

}
8 changes: 2 additions & 6 deletions src/main/java/site/youtogether/playlist/PlayingVideo.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ public PlayingVideo(String roomCode, Video video, MessageService messageService,
this.playlistService = playlistService;
}

public void start(double time) {
public void startAt(double time) {
timer.cancel();
timer.purge();
currentTime = Math.round(time * 100) / 100.0;
createTimer(playerRate);
}

public void pause(double time) {
public void pauseAt(double time) {
timer.cancel();
timer.purge();
currentTime = Math.round(time * 100) / 100.0;
Expand All @@ -75,10 +75,6 @@ public void changeRate(double playerRate) {
createTimer(playerRate);
}

public void changeCurrentTime(double time) {
this.currentTime = time;
}

private void createTimer(double playerRate) {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,11 @@ public void manageVideo(VideoSyncInfoMessage videoSyncInfoMessage) {

PlayerState playerState = videoSyncInfoMessage.getPlayerState();
if (playerState == PlayerState.PAUSE) {
playingVideo.pause(videoSyncInfoMessage.getPlayerCurrentTime());
playingVideo.pauseAt(videoSyncInfoMessage.getPlayerCurrentTime());
} else if (playerState == PlayerState.RATE) {
playingVideo.changeRate(videoSyncInfoMessage.getPlayerRate());
} else if (playerState == PlayerState.PLAY) {
playingVideo.start(videoSyncInfoMessage.getPlayerCurrentTime());
} else if (playerState == PlayerState.SKIP) {
playingVideo.changeCurrentTime(videoSyncInfoMessage.getPlayerCurrentTime());
playingVideo.startAt(videoSyncInfoMessage.getPlayerCurrentTime());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public Optional<PlayingVideo> findById(String roomCode) {

public void saveAndPlay(PlayingVideo playingVideo) {
storage.put(playingVideo.getRoomCode(), playingVideo);
playingVideo.start(0);
playingVideo.startAt(0);
}

public void delete(String roomCode) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.springframework.stereotype.Service;

import lombok.RequiredArgsConstructor;
import site.youtogether.exception.user.UserNicknameDuplicateException;
import site.youtogether.exception.user.UserNoExistenceException;
import site.youtogether.message.AlarmMessage;
import site.youtogether.message.application.MessageService;
Expand Down Expand Up @@ -54,4 +55,10 @@ public Participant changeUserRole(Long userId, UserRoleChangeForm form) {
return new Participant(targetUser);
}

public void checkUserNicknameDuplication(String nickname) {
if (uniqueNicknameStorage.exist(nickname)) {
throw new UserNicknameDuplicateException();
}
}

}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package site.youtogether.user.presentation;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;
Expand All @@ -21,6 +23,14 @@ public class UserController {

private final UserService userService;

@GetMapping("/users/nicknames/check")
public ResponseEntity<ApiResponse<Void>> checkUserNicknameDuplication(@RequestParam @Valid NicknameInput nickname) {
userService.checkUserNicknameDuplication(nickname.getNewNickname());

return ResponseEntity.ok()
.body(ApiResponse.ok(ResponseResult.USER_NICKNAME_IS_UNIQUE, null));
}

@PatchMapping("/users")
public ResponseEntity<ApiResponse<Participant>> changeUserNickname(@UserTracking Long userId, @RequestBody @Valid NicknameInput form) {
Participant participantInfo = userService.changeUserNickname(userId, form.getNewNickname());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public enum ResponseResult {
// User
USER_NICKNAME_CHANGE_SUCCESS("유저 닉네임 변경에 성공했습니다"),
USER_ROLE_CHANGE_SUCCESS("유저의 역할 변경에 성공했습니다"),
USER_NICKNAME_IS_UNIQUE("사용 가능한 닉네임입니다"),

// Playlist
PLAYLIST_ADD_SUCCESS("플레이리스트에 비디오 추가를 성공했습니다"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,84 @@

class UserControllerTest extends RestDocsSupport {

@Test
@DisplayName("닉네임 중복 검사 성공")
void checkNicknameDuplication() throws Exception {
// Setting session cookie for request
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NSJ9.XJHPNpgWMty0iKr1FQKCBeOapvlqk1RjcPQUzT2dFlA";
Cookie sessionCookie = new Cookie(cookieProperties.getName(), token);

// Setting new user nickname for request
String newNickname = "new nickname";

given(jwtService.parse(eq(token)))
.willReturn(1L);
given(userStorage.existsById(eq(1L)))
.willReturn(true);

// when // then
mockMvc.perform(get("/users/nicknames/check")
.param("nickname", newNickname)
.cookie(sessionCookie))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(HttpStatus.OK.value()))
.andExpect(jsonPath("$.status").value(HttpStatus.OK.getReasonPhrase()))
.andExpect(jsonPath("$.result").value(ResponseResult.USER_NICKNAME_IS_UNIQUE.getDescription()))
.andDo(document("check-nickname-success",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("code").type(JsonFieldType.NUMBER).description("코드"),
fieldWithPath("status").type(JsonFieldType.STRING).description("상태"),
fieldWithPath("result").type(JsonFieldType.STRING).description("결과"),
fieldWithPath("data").type(JsonFieldType.NULL).description("응답 데이터")
)
));
}

@Test
@DisplayName("닉네임 중복 검사 실패")
void checkNicknameDuplicationFail() throws Exception {
// Setting session cookie for request
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NSJ9.XJHPNpgWMty0iKr1FQKCBeOapvlqk1RjcPQUzT2dFlA";
Cookie sessionCookie = new Cookie(cookieProperties.getName(), token);

// Setting new user nickname for request
String newNickname = "new nickname";

given(jwtService.parse(eq(token)))
.willReturn(1L);
given(userStorage.existsById(eq(1L)))
.willReturn(true);
doThrow(new UserNicknameDuplicateException())
.when(userService).checkUserNicknameDuplication(any());

// when // then
mockMvc.perform(get("/users/nicknames/check")
.param("nickname", newNickname)
.cookie(sessionCookie))
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(HttpStatus.BAD_REQUEST.value()))
.andExpect(jsonPath("$.status").value(HttpStatus.BAD_REQUEST.getReasonPhrase()))
.andExpect(jsonPath("$.result").value(ResponseResult.EXCEPTION_OCCURRED.getDescription()))
.andExpect(jsonPath("$.data[0].type").value(UserNicknameDuplicateException.class.getSimpleName()))
.andExpect(jsonPath("$.data[0].message").value(ErrorType.USER_NICKNAME_DUPLICATE.getMessage()))
.andDo(document("check-nickname-fail",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("code").type(JsonFieldType.NUMBER).description("코드"),
fieldWithPath("status").type(JsonFieldType.STRING).description("상태"),
fieldWithPath("result").type(JsonFieldType.STRING).description("결과"),
fieldWithPath("data").type(JsonFieldType.ARRAY).description("응답 데이터"),
fieldWithPath("data[].type").type(JsonFieldType.STRING).description("오류 타입"),
fieldWithPath("data[].message").type(JsonFieldType.STRING).description("오류 메시지")
)
));
}

@Test
@DisplayName("닉네임 변경 성공")
void changeNickname() throws Exception {
Expand Down
Loading