Skip to content

Commit

Permalink
Merge pull request #219 from boostcampwm2023/BE-CreateChatRoom-#218
Browse files Browse the repository at this point in the history
[BE/#218] 채팅방 만들기 구현
  • Loading branch information
namewhat99 authored Nov 29, 2023
2 parents fba161d + db998de commit 2240844
Show file tree
Hide file tree
Showing 6 changed files with 98 additions and 6 deletions.
11 changes: 11 additions & 0 deletions BE/src/chat/chat.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,21 @@ import {
Patch,
Param,
Delete,
UseGuards,
} from '@nestjs/common';
import { ChatService } from './chat.service';
import { AuthGuard } from '../utils/auth.guard';
import { UserHash } from '../utils/auth.decorator';
import { CreateRoomDto } from './createRoom.dto';

@Controller('chat')
export class ChatController {
constructor(private readonly chatService: ChatService) {}

// 게시글에서 채팅하기 버튼 누르면 채팅방 만드는 API (테스트는 안해봄, 좀더 수정 필요)
@Post('room')
@UseGuards(AuthGuard)
async roomCreate(@Body() body: CreateRoomDto, @UserHash() userId: string) {
await this.chatService.createRoom(body.post_id, userId, body.writer);
}
}
4 changes: 4 additions & 0 deletions BE/src/chat/chat.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ import { Module } from '@nestjs/common';
import { ChatService } from './chat.service';
import { ChatController } from './chat.controller';
import { ChatsGateway } from './chats.gateway';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ChatRoomEntity } from '../entities/chatRoom.entity';
import { PostEntity } from '../entities/post.entity';

@Module({
imports: [TypeOrmModule.forFeature([ChatRoomEntity, PostEntity])],
controllers: [ChatController],
providers: [ChatService, ChatsGateway],
})
Expand Down
22 changes: 21 additions & 1 deletion BE/src/chat/chat.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,24 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PostEntity } from '../entities/post.entity';
import { Repository } from 'typeorm';
import { ChatRoomEntity } from '../entities/chatRoom.entity';

@Injectable()
export class ChatService {}
export class ChatService {
constructor(
@InjectRepository(ChatRoomEntity)
private chatRoomRepository: Repository<ChatRoomEntity>,
@InjectRepository(PostEntity)
private postRepository: Repository<PostEntity>,
) {}
async createRoom(postId: number, userId: string, writerId: string) {
const chatRoom = new ChatRoomEntity();
chatRoom.post_id = postId;
chatRoom.writer = writerId;
chatRoom.sender = userId;
const newChatRoom = await this.chatRoomRepository.save(chatRoom);
// 좀 더 가공해서 채팅 룸에 대한 정보 줄 수 있게 수정하면 될듯
return newChatRoom;
}
}
18 changes: 13 additions & 5 deletions BE/src/chat/chats.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export class ChatsGateway implements OnGatewayConnection {
@WebSocketServer() server: Server;
private rooms = new Map<string, Set<Websocket>>();
handleConnection(client: Websocket) {
// 인증 로직
console.log(`on connnect : ${client}`);
}

Expand All @@ -29,28 +30,35 @@ export class ChatsGateway implements OnGatewayConnection {
) {
console.log(message);
const room = this.rooms.get(message['room']);
const sender = message['sender'];
room.forEach((people) => {
if (people !== client) people.send(JSON.stringify(message['message']));
if (people !== client)
people.send(JSON.stringify({ sender, message: message['message'] }));
});
}

@SubscribeMessage('join-room')
joinRoom(
@MessageBody() roomName: string,
@MessageBody() message: object,
@ConnectedSocket() client: Websocket,
) {
// MessageBody 에 있는 (a , b) 쌍을 통해 DB 에서 해당 방을 찾아서 roomName 을 설정해야함

const roomName = message['room'];
if (this.rooms.has(roomName)) this.rooms.get(roomName).add(client);
else this.rooms.set(roomName, new Set([client]));
}

@SubscribeMessage('leave-room')
leaveRoom(
@MessageBody() roomName: string,
@MessageBody() message: object,
@ConnectedSocket() client: Websocket,
) {
this.rooms.get(roomName).delete(client);
const roomName = message['room'];
const room = this.rooms.get(roomName);
room.delete(client);
if (room.size === 0) {
this.rooms.delete(roomName);
}
console.log(this.rooms);
}
}
8 changes: 8 additions & 0 deletions BE/src/chat/createRoom.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { IsNumber, IsString } from 'class-validator';

export class CreateRoomDto {
@IsNumber()
post_id: number;
@IsString()
writer: string;
}
41 changes: 41 additions & 0 deletions BE/src/entities/chatRoom.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import {
Column,
CreateDateColumn,
DeleteDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { PostEntity } from './post.entity';
import { BlockUserEntity } from './blockUser.entity';
import { BlockPostEntity } from './blockPost.entity';

@Entity('chat_room')
export class ChatRoomEntity {
@PrimaryGeneratedColumn()
id: number;

@Column({ type: 'int' })
post_id: number;

@Column({ length: 45, nullable: false, charset: 'utf8', unique: true })
writer: string;

@Column({ length: 45, nullable: false, charset: 'utf8', unique: true })
sender: string;

@CreateDateColumn({
type: 'timestamp',
nullable: false,
})
create_date: Date;

@UpdateDateColumn({
type: 'timestamp',
nullable: true,
})
update_date: Date;

@DeleteDateColumn()
delete_date: Date;
}

0 comments on commit 2240844

Please sign in to comment.