Skip to content

Commit

Permalink
feat: 입장 알림, 메시지 전송 기능 (유저 이름x) (#112)
Browse files Browse the repository at this point in the history
  • Loading branch information
suubinkim committed Jan 16, 2022
1 parent ec41123 commit c208bda
Show file tree
Hide file tree
Showing 10 changed files with 96 additions and 46 deletions.
17 changes: 12 additions & 5 deletions src/main/java/shop/fevertime/backend/api/ChatApiController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,27 @@
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import shop.fevertime.backend.dto.ChatMessageDto;
import shop.fevertime.backend.dto.MessageDto;

@Controller
@RequiredArgsConstructor
public class ChatApiController {

private final SimpMessageSendingOperations messagingTemplate;

@MessageMapping("/chat/enter")
public void enter(ChatMessageDto messageDto){

messagingTemplate.convertAndSend("/sub/chat/room/" + messageDto.getRoomId(), messageDto);
}

@MessageMapping("/chat/message")
public void addUser(@RequestBody ChatMessageDto messageDto) {
if (ChatMessageDto.MessageType.ENTER.equals(messageDto.getType()))
messageDto.setMessage(messageDto.getSender() + "님이 입장하셨습니다.");
public void message(ChatMessageDto messageDto) {
messagingTemplate.convertAndSend("/sub/chat/room/" + messageDto.getRoomId(), messageDto);
}

@MessageMapping("/chat/exit")
public void exit(ChatMessageDto messageDto) {
messagingTemplate.convertAndSend("/sub/chat/room/" + messageDto.getRoomId(), messageDto);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import shop.fevertime.backend.domain.ChatRoom;
import shop.fevertime.backend.dto.ChatRoomDto;
import shop.fevertime.backend.dto.response.ChatRoomResponseDto;
import shop.fevertime.backend.dto.request.ChatRoomRequestDto;
import shop.fevertime.backend.dto.response.ResultResponseDto;
import shop.fevertime.backend.repository.ChatRoomRepository;
import shop.fevertime.backend.security.UserDetailsImpl;
Expand All @@ -18,34 +17,41 @@
@RequestMapping("/chat")
public class ChatRoomApiController {

private final ChatRoomRepository chatRoomRepository;
private final ChatRoomService chatRoomService;

/**
* 채팅방 목록 조회 API
*/
//반환값 dto로 변경해야함
@GetMapping("/rooms")
public List<ChatRoom> getRooms() {
public List<ChatRoomResponseDto> getRooms() {
return chatRoomService.getAllRooms();
}

/**
* 채팅방 생성 API
*/
@PostMapping("/room")
public ResultResponseDto createRoom(@RequestBody ChatRoomDto chatRoomDto,
public ResultResponseDto createRoom(@RequestBody ChatRoomRequestDto chatRoomDto,
@AuthenticationPrincipal UserDetailsImpl userDetails) {
chatRoomService.createRoom(chatRoomDto, userDetails.getUser());
return new ResultResponseDto("success", "채팅 방이 생성되었습니다.");
}

/**
* 채팅방 상세 조회 API
*/
@GetMapping("/room/{roomId}")
public ChatRoomResponseDto getRoom(@PathVariable Long roomId) {
return chatRoomService.getRoom(roomId);
}

/**
* 채팅방 삭제 API
*/
@DeleteMapping("/room/{roomId}")
public ResultResponseDto deleteRoom(@PathVariable Long roomId,
@AuthenticationPrincipal UserDetailsImpl userDetails) {
@AuthenticationPrincipal UserDetailsImpl userDetails) {
chatRoomService.deleteRoom(roomId, userDetails.getUser());
return new ResultResponseDto("success", "채팅 방이 삭제되었습니다.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ protected void configure(HttpSecurity http) throws Exception {
.antMatchers(HttpMethod.GET, "/challenges/{challengeId}/user").authenticated()
.antMatchers(HttpMethod.GET, "/challenges/**").permitAll()
.antMatchers(HttpMethod.GET, "/feeds/**").permitAll()
.antMatchers(HttpMethod.GET, "/chat/**").permitAll()
.antMatchers(HttpMethod.GET, "/search/**").permitAll()
.antMatchers(HttpMethod.GET, "/sub/**").permitAll()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/login/kakao").permitAll()
.antMatchers("/websocket/**").permitAll()
.antMatchers("/ws-stomp/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
Expand Down
16 changes: 8 additions & 8 deletions src/main/java/shop/fevertime/backend/domain/ChatRoom.java
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
package shop.fevertime.backend.domain;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import shop.fevertime.backend.dto.ChatRoomDto;

import javax.persistence.*;

@Getter
@NoArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
public class ChatRoom extends BaseTimeEntity {
public class ChatRoom extends BaseTimeEntity{

@Id // ID 값, Primary Key로 사용하겠다는 뜻입니다.
@GeneratedValue(strategy = GenerationType.AUTO) // 자동 증가 명령입니다.
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "room_id")
private Long id;

@Column // 컬럼 값이고 반드시 값이 존재해야 함을 나타냅니다.
@Column(nullable = false)
private String name;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;

public ChatRoom(ChatRoomDto chatRoomDto, User user) {
this.name = chatRoomDto.getName();
public ChatRoom(String name, User user) {
this.name = name;
this.user = user;
}

Expand Down
6 changes: 0 additions & 6 deletions src/main/java/shop/fevertime/backend/dto/ChatMessageDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,6 @@
@Getter
@Setter
public class ChatMessageDto {
//메세지 타입 : 입장, 채팅
public enum MessageType {
ENTER, TALK
}
private MessageType type; //메세지 타입
private String roomId;
private String sender;
private String message;
}
10 changes: 0 additions & 10 deletions src/main/java/shop/fevertime/backend/dto/ChatRoomDto.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package shop.fevertime.backend.dto.request;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
public class ChatRoomRequestDto {
private String name;

public ChatRoomRequestDto(String name) {
this.name = name;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package shop.fevertime.backend.dto.response;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import shop.fevertime.backend.domain.ChatRoom;

import java.time.format.DateTimeFormatter;

@Getter
@Setter
@NoArgsConstructor
public class ChatRoomResponseDto {
private Long roomId;
private String name;
private String createdDate;

public ChatRoomResponseDto(ChatRoom chatRoom) {
this.roomId = chatRoom.getId();
this.name= chatRoom.getName();
this.createdDate = chatRoom.getCreatedDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));;
}

}
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package shop.fevertime.backend.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import shop.fevertime.backend.domain.ChatRoom;
import shop.fevertime.backend.domain.User;

@Repository
public interface ChatRoomRepository extends JpaRepository<ChatRoom, Long> {
ChatRoom findByIdAndUser(Long roomId, User user);
}
28 changes: 21 additions & 7 deletions src/main/java/shop/fevertime/backend/service/ChatRoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.fevertime.backend.domain.ChatRoom;
import shop.fevertime.backend.domain.User;
import shop.fevertime.backend.dto.ChatRoomDto;
import shop.fevertime.backend.dto.response.ChatRoomResponseDto;
import shop.fevertime.backend.dto.request.ChatRoomRequestDto;
import shop.fevertime.backend.exception.ApiRequestException;
import shop.fevertime.backend.repository.ChatRoomRepository;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
Expand All @@ -19,16 +21,28 @@ public class ChatRoomService {

private final ChatRoomRepository chatRoomRepository;

//반환값 dto로 바꿔야함
public List<ChatRoom> getAllRooms() {
return chatRoomRepository.findAll(Sort.by(Sort.Direction.DESC, "createdDate"));
@Transactional
public List<ChatRoomResponseDto> getAllRooms() {
return chatRoomRepository.findAll()
.stream()
.map(ChatRoomResponseDto::new)
.collect(Collectors.toList());
}

@Transactional
public void createRoom(ChatRoomDto chatRoomDto, User user) {
chatRoomRepository.save(new ChatRoom(chatRoomDto, user));
public void createRoom(ChatRoomRequestDto chatRoomDto, User user) {
chatRoomRepository.save(new ChatRoom(chatRoomDto.getName(), user));
}

@Transactional
public ChatRoomResponseDto getRoom(Long roomId) {
ChatRoom byId = chatRoomRepository.findById(roomId).orElseThrow(
() -> new ApiRequestException("해당 채팅방이 없습니다.")
);
return new ChatRoomResponseDto(byId);
}


@Transactional
public void deleteRoom(Long roomId, User user) {
ChatRoom chatRoom = chatRoomRepository.findByIdAndUser(roomId, user);
Expand Down

0 comments on commit c208bda

Please sign in to comment.