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

메시지 전송 api 구현 #24

Merged
merged 4 commits into from
Aug 30, 2020
Merged

메시지 전송 api 구현 #24

merged 4 commits into from
Aug 30, 2020

Conversation

so3500
Copy link
Contributor

@so3500 so3500 commented Aug 29, 2020

🐣 변경 사항

POST /api/rooms/{roomId}/messages 구현

⚽ 기능 설명

채팅방에서 주고받는 메시지 저장 기능

🏷 연관 이슈

#19

🧢 체크 리스트

  • 테스트 코드를 포함하고 있나요?
  • 공통된 코드 스타일을 따르 있나요?

@so3500 so3500 self-assigned this Aug 29, 2020
Comment on lines +31 to +51
@Test
@Sql("/test-sql/messages.sql")
void createMessage() throws Exception {

// given
MessageRequest req = new MessageRequest();
req.setContents("hi hello");

final String body = objectMapper.writeValueAsString(req);

// when
ResultActions action = mockMvc.perform(
post("/api/rooms/{roomId}/messages", 1)
.contentType(MediaType.APPLICATION_JSON)
.content(body));

// then
action.andDo(print())
.andExpect(status().isCreated())
.andExpect(jsonPath("$.contents").value(req.getContents()));
}
Copy link
Contributor Author

@so3500 so3500 Aug 29, 2020

Choose a reason for hiding this comment

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

이 메서드를 MessageCreationTest 에 추가한 이유

이 테스트를 RoomControllerIntegrationTest 에 추가할 때 RoomControllerIntegrationTest#shouldGetMessageList_inRoomIdWith1 가 영향 받음

하나의 클래스에서 처리할 수 없을지 고민 필요

response

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json;charset=UTF-8"]
     Content type = application/json
             Body = [{"id":1,"contents":"foo","createdAt":[2020,8,1,0,0],"messageType":"TEXT"},{"id":3,"contents":"hi hello","createdAt":[2020,8,30,1,5,8,114499000],"messageType":"TEXT"},{"id":4,"contents":"foo","createdAt":[2020,8,1,0,0],"messageType":"TEXT"}]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

error log

JSON path "$.*"
Expected: a collection with size <1>
     but: collection size was <3>
java.lang.AssertionError: JSON path "$.*"
Expected: a collection with size <1>
     but: collection size was <3>
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
	at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:73)
	at org.springframework.test.web.servlet.result.JsonPathResultMatchers.lambda$value$0(JsonPathResultMatchers.java:87)
	at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
	at web.chat.backend.controller.RoomControllerIntegrationTest.shouldGetMessageList_inRoomIdWith1(RoomControllerIntegrationTest.java:58)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at 
...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

#25 에서 고민해보기

Comment on lines +26 to +29
public Room getOrThrow(Long roomId) {
return roomRepository.findById(roomId)
.orElseThrow(() -> new NotFoundException(String.format("Room [id:%d] not found", roomId)));
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

유효하지 않는 roomId 를 받았을 때 null 을 리턴하지 않고 NotFoundException 을 발생시켜 각 계층 간 null을 주고받는 상황을 방지

Copy link
Collaborator

Choose a reason for hiding this comment

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

exists() 사용하지 않고 Optional 으로 하니까 깔끔하네 굿굿 👍 👍

public List<Message> getMessagesBy(Long roomId) {
if (!messageRepository.existsByRoomId(roomId)) {
throw new NotFoundException(roomId);
}
return messageRepository.findAllByRoomId(roomId);
}


import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Entity
@EntityListeners(AuditingEntityListener.class)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Copy link
Collaborator

Choose a reason for hiding this comment

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

Copy link
Contributor Author

Choose a reason for hiding this comment

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

👍 나중에 공통 프로퍼티는 BaseEntity 클래스로 빼는 방법도 고려해봐야겠다

@so3500 so3500 added feature new feature fix bug fix labels Aug 29, 2020
Copy link
Collaborator

@raccoonback raccoonback left a comment

Choose a reason for hiding this comment

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

👍 👍

Comment on lines +26 to +29
public Room getOrThrow(Long roomId) {
return roomRepository.findById(roomId)
.orElseThrow(() -> new NotFoundException(String.format("Room [id:%d] not found", roomId)));
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

exists() 사용하지 않고 Optional 으로 하니까 깔끔하네 굿굿 👍 👍

public List<Message> getMessagesBy(Long roomId) {
if (!messageRepository.existsByRoomId(roomId)) {
throw new NotFoundException(roomId);
}
return messageRepository.findAllByRoomId(roomId);
}

@so3500 so3500 merged commit bd1e2ed into master Aug 30, 2020
@so3500 so3500 deleted the feat/add-message branch August 30, 2020 02:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature new feature fix bug fix
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants