Skip to content

Commit

Permalink
Merge pull request #236 from boostcampwm2023/BE-saveChatToDB-#233
Browse files Browse the repository at this point in the history
[BE/#223] Feat : 채팅 DB 에 저장
  • Loading branch information
koomin1227 authored Nov 30, 2023
2 parents 295c343 + 4aed13d commit d2e3d89
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 24 deletions.
2 changes: 1 addition & 1 deletion BE/src/chat/chat.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ export class ChatController {
@UseGuards(AuthGuard)
async roomCreate(@Body() body: CreateRoomDto, @UserHash() userId: string) {
console.log(userId);
await this.chatService.createOrFindRoom(body.post_id, userId, body.writer);
await this.chatService.createRoom(body.post_id, userId, body.writer);
}
}
3 changes: 2 additions & 1 deletion BE/src/chat/chat.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import { ChatsGateway } from './chats.gateway';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ChatRoomEntity } from '../entities/chatRoom.entity';
import { PostEntity } from '../entities/post.entity';
import { ChatEntity } from 'src/entities/chat.entity';

@Module({
imports: [TypeOrmModule.forFeature([ChatRoomEntity, PostEntity])],
imports: [TypeOrmModule.forFeature([ChatRoomEntity, PostEntity, ChatEntity])],
controllers: [ChatController],
providers: [ChatService, ChatsGateway],
})
Expand Down
36 changes: 19 additions & 17 deletions BE/src/chat/chat.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PostEntity } from '../entities/post.entity';
import { Repository } from 'typeorm';
import { In, Repository } from 'typeorm';
import { ChatRoomEntity } from '../entities/chatRoom.entity';
import { ChatEntity } from 'src/entities/chat.entity';
import { ChatDto } from './dto/chat.dto';

@Injectable()
export class ChatService {
Expand All @@ -11,24 +13,24 @@ export class ChatService {
private chatRoomRepository: Repository<ChatRoomEntity>,
@InjectRepository(PostEntity)
private postRepository: Repository<PostEntity>,
@InjectRepository(ChatEntity)
private chatRepository: Repository<ChatEntity>,
) {}

async createOrFindRoom(postId: number, userId: string, writerId: string) {
const roomNumber = await this.chatRoomRepository.findOne({
where: { writer: writerId, user: userId, post_id: postId },
}); // 해당 게시글과 사람들에 대한 채팅방이 있는지 확인한다

if (roomNumber) {
return roomNumber; // 있으면 채팅방 번호 리턴
} else {
const chatRoom = new ChatRoomEntity();
chatRoom.post_id = postId;
chatRoom.writer = writerId;
chatRoom.user = userId;
const newChatRoom = await this.chatRoomRepository.save(chatRoom); // 없으면 새로 만들어서 저장후 리턴
return newChatRoom;
}
async saveMessage(message: ChatDto) {
const chat = new ChatEntity();
chat.sender = message.sender;
chat.message = message.message;
chat.chat_room = message.room_id;
await this.chatRepository.save(chat);
}

//이후에 채팅과 Join 해서 채팅 목록도 가져와야함
async createRoom(postId: number, userId: string, writerId: string) {
const chatRoom = new ChatRoomEntity();
chatRoom.post_id = postId;
chatRoom.writer = writerId;
chatRoom.user = userId;
const newChatRoom = await this.chatRoomRepository.save(chatRoom); // 없으면 새로 만들어서 저장후 리턴
return newChatRoom;
}
}
13 changes: 8 additions & 5 deletions BE/src/chat/chats.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ import {
} from '@nestjs/websockets';
import { Server, Websocket } from 'ws';
import { ChatService } from './chat.service';
import { ChatDto } from './dto/chat.dto';

@WebSocketGateway({
path: 'chats',
})
export class ChatsGateway implements OnGatewayConnection {
@WebSocketServer() server: Server;
private rooms = new Map<string, Set<Websocket>>();
private rooms = new Map<number, Set<Websocket>>();

constructor(private readonly chatService: ChatService) {}
handleConnection(client: Websocket) {
Expand All @@ -27,25 +28,27 @@ export class ChatsGateway implements OnGatewayConnection {
}

@SubscribeMessage('send-message')
sendMessage(
@MessageBody() message: object,
async sendMessage(
@MessageBody() message: ChatDto,
@ConnectedSocket() client: Websocket,
) {
console.log(message);
const room = this.rooms.get(message['room']);
const room = this.rooms.get(message['room_id']);
const sender = message['sender'];
console.log(room);
room.forEach((people) => {
if (people !== client)
people.send(JSON.stringify({ sender, message: message['message'] }));
});
await this.chatService.saveMessage(message);
}

@SubscribeMessage('join-room')
joinRoom(
@MessageBody() message: object,
@ConnectedSocket() client: Websocket,
) {
const roomName = message['room'];
const roomName = message['room_id'];
if (this.rooms.has(roomName)) this.rooms.get(roomName).add(client);
else this.rooms.set(roomName, new Set([client]));
}
Expand Down
12 changes: 12 additions & 0 deletions BE/src/chat/dto/chat.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { IsString } from 'class-validator';

export class ChatDto {
@IsString()
sender: string;

@IsString()
message: string;

@IsString()
room_id: number;
}

0 comments on commit d2e3d89

Please sign in to comment.