Skip to content

Commit

Permalink
Merge pull request #135 from LocalMingle/dev
Browse files Browse the repository at this point in the history
[수정] 배포 오류로 chat 코드 롤백
  • Loading branch information
HeeDragoN1123 authored Nov 3, 2023
2 parents 7357e65 + d10a00b commit 72bb4eb
Show file tree
Hide file tree
Showing 7 changed files with 194 additions and 363 deletions.
28 changes: 14 additions & 14 deletions src/chats/chats.gateway.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ChatsGateway } from './chats.gateway';
// import { Test, TestingModule } from '@nestjs/testing';
// import { ChatsGateway } from './chats.gateway';

describe('ChatsGateway', () => {
let gateway: ChatsGateway;
// describe('ChatsGateway', () => {
// let gateway: ChatsGateway;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ChatsGateway],
}).compile();
// beforeEach(async () => {
// const module: TestingModule = await Test.createTestingModule({
// providers: [ChatsGateway],
// }).compile();

gateway = module.get<ChatsGateway>(ChatsGateway);
});
// gateway = module.get<ChatsGateway>(ChatsGateway);
// });

it('should be defined', () => {
expect(gateway).toBeDefined();
});
});
// it('should be defined', () => {
// expect(gateway).toBeDefined();
// });
// });
186 changes: 81 additions & 105 deletions src/chats/chats.gateway.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { Chatting } from './models/chattings.model';
import { InjectModel } from '@nestjs/mongoose';
import { Logger } from '@nestjs/common';
import { Socket, Server } from 'socket.io';
import {
ConnectedSocket,
MessageBody,
Expand All @@ -9,129 +12,102 @@ import {
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';
import { ChatsService } from './chats.service';
import { IMessage, IRoomRequest } from './interfaces/chats.interface';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { LocalDateTime } from '@js-joda/core';
import { Chatting } from './models/chattings.model';

// import { IMessage } from './room.chats.interface';
// import { LocalDateTime } from '@js-joda/core';
@WebSocketGateway({
namespace: 'chattings',
//WebSocket 서버가 모든 원격 호스트로부터의 연결을 허용
cors: true,
allowEIO3: true,
cors: {
origin: [
'http://localhost:5173',
'https://d2r603zvpf912o.cloudfront.net',
'https://totobon.store',
'https://local-mingle-fe.vercel.app',
],
methods: ['GET', 'POST'],
credentials: true,
},
})
export class ChatsGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer() server: Server;
private logger: Logger = new Logger('AppGateway');

//의존성 주입
@InjectModel(Chatting.name) private readonly chattingModel: Model<Chatting>;
constructor(private readonly chatsService: ChatsService) {}

//유저가 연결 되었을때 기존은 socket: Socket
handleConnection(@ConnectedSocket() client: Socket) {
this.logger.log(`Client connected: ${client.id}`);
private logger = new Logger('chat');
constructor(
@InjectModel(Chatting.name) private readonly chattingModel: Model<Chatting>,
@InjectModel(Socket.name)
private readonly socketModel: Model<Socket>
) {
this.logger.log('constructor');
}

//유저가 연결해제 되었을때 로직
handleDisconnect(@ConnectedSocket() client: Socket) {
this.logger.log(`disconnected: ${client.id}`);
this.chatsService.disconnectClient(client, this.server);
// WebSocketGateway가 초기화될 때 실행되는 메소드
// WebSocketGateway가 초기화되면 로그를 출력합니다.
afterInit() {
this.logger.log('init');
}
// 클라이언트와의 연결이 해제될 때 실행되는 메소드
// 클라이언트 소켓 연결이 끊기면 roomChatsService의 handleDisconnect 메소드 호출
async handleDisconnect(@ConnectedSocket() socket: Socket) {
const user = await this.socketModel.findOne({ id: socket.id });
if (user) {
socket.broadcast.emit('disconnect_user', user.data);
await user.deleteOne();
}
this.logger.log(`disconnected : ${socket.id} ${socket.nsp.name}`);
// this.logger.log(`disconnected : ${socket.id} ${socket.nsp.name}`);
// await this.roomChatsService.handleDisconnect(socket);
// this.logger.log(`disconnected : ${socket.id} ${socket.nsp.name}`);
}
// 클라이언트와의 연결이 수립될 때 실행되는 메소드
// 클라이언트가 연결되면 해당 클라이언트의 ID와 네임스페이스 정보를 로그에 출력
async handleConnection(@ConnectedSocket() socket: Socket) {
this.logger.log(`connected : ${socket.id} ${socket.nsp.name}`);
// await this.logger.log(`connected : ${socket.id} ${socket.nsp.name}`);
}
// 클라이언트가 'join_room' 메시지를 보낼 때 실행되는 메소드
@SubscribeMessage('join_room')
async handleJoinRoom(
@MessageBody()
payload: { nickname: string; roomId: number; profileImg: string },
@ConnectedSocket() socket: Socket
) {
socket.join(String(payload.roomId));
this.logger.log(
`Joined room: ${payload.roomId}, Nickname: ${payload.nickname}`
);
this.server.to(String(payload.roomId)).emit('user_connected', payload);
}

// 클라이언트가 'submit_chat' 메시지를 보낼 때 실행되는 메소드 (채팅을하고 그걸 다른유저에게 브로드캐스팅)
// 클라이언트가 'submit_chat' 메시지를 보낼 때 실행되는 메소드
@SubscribeMessage('submit_chat')
async handleSubmitChat(
@MessageBody() { roomId, nickname, profileImg, message }: IMessage
): Promise<void> {
const localDateTime = LocalDateTime.now().plusHours(9);
const period = localDateTime.hour() < 12 ? 'AM' : 'PM';
const formattedHour = localDateTime.hour() % 12 || 12;
const minute = localDateTime.minute().toString().padStart(2, '0');
const messageData: IMessage = {
message,
time: `${formattedHour}:${minute} ${period}`,
nickname,
roomId,
profileImg,
};
@MessageBody()
messageData: {
message: string;
nickname: string;
profileImg: string;
time: string;
roomId: number;
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@ConnectedSocket() _socket: Socket
) {
this.logger.log(
`New chat in room ${messageData.roomId}: ${messageData.message}`
);

//const socketObj = await this.socketModel.findOne({ Socket });
const socketObj = await this.socketModel.findOne({ id: _socket.id });

// MongoDB에 채팅 메시지 저장
await this.chattingModel.create({
// user: socketObj, // 메세지를보낸 소켓 정보
nickname: messageData.nickname, //메세지를 보낸 사용자의 닉네임
profileImg: messageData.profileImg, //메세지를 보낸 사용자의 프로필 이미지
roomId: messageData.roomId, // 채팅이 속한 방의 ID
time: messageData.time, // 메세지를 송신한 시간
chat: messageData.message, // 실제 채팅 메시지 내용.
created: new Date(), // 채팅 생성 시간 기록
user: socketObj,
nickname: messageData.nickname,
profileImg: messageData.profileImg,
roomId: messageData.roomId,
time: messageData.time,
chat: messageData.message, // 수정: messageData.message를 사용하여 채팅 저장
});

this.logger.log(messageData);
this.server.to(String(messageData.roomId)).emit('new_chat', messageData);
}

// 일정기간(3일)이 지난 채팅을 db에서 삭제
async deleteOldChats() {
// 72시간(3일) 이상 지난 채팅 삭제
const chatScheduler = new Date();
// chatScheduler.setDate(chatScheduler.getDate() - 3); //3일
//chatScheduler.setHours(chatScheduler.getHours() - 72); // 72시간
chatScheduler.setMinutes(chatScheduler.getMinutes() - 2); // 4320분(3일) 테스트 2분
await this.chattingModel.deleteMany({ created: { $lt: chatScheduler } });
}

// 유저가 방에 참석할때
@SubscribeMessage('join_room')
async handleJoinRoom(
@ConnectedSocket() client: Socket,
@MessageBody() { nickname, roomId, profileImg, userId }: IRoomRequest
): Promise<void> {
client.leave(client.id);
client.join(String(roomId));

// 이전 채팅 내용을 불러옵니다.
const chatHistory = await this.chatsService.getChatHistory(roomId);

// 이전 채팅 내용과 함께 사용자 정보를 클라이언트에게 전송합니다.
client.emit('chat_history', chatHistory);
this.chatsService.joinRoom(client, this.server, {
nickname,
roomId,
profileImg,
userId,
});
}

// 유저가 방을 삭제할때
@SubscribeMessage('remove_room')
handleRemoveRoom(
@ConnectedSocket() client: Socket,
@MessageBody() { roomId }: IRoomRequest
): void {
this.chatsService.removeRoom(client, this.server, roomId);
}

// 유저가 방을 떠날때
@SubscribeMessage('leave_room')
handleLeaveRoom(
@ConnectedSocket() client: Socket,
@MessageBody() { roomId }: IRoomRequest
): void {
client.leave(String(roomId));
this.chatsService.leaveRoom(client, this.server, roomId);
}

// WebSocketGateway가 초기화될 때 실행되는 메소드
// WebSocketGateway가 초기화되면 로그를 출력합니다.
afterInit() {
this.logger.log('init');
}
} // 끝
}
8 changes: 4 additions & 4 deletions src/chats/chats.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { SocketSchema, Socket as SocketModel } from './models/sockets.model';
import { Module } from '@nestjs/common';
import { ChatsGateway } from './chats.gateway';
import { ChatsService } from './chats.service';
import { Chatting, ChattingSchema } from './models/chattings.model';
import { MongooseModule } from '@nestjs/mongoose';
import { SocketSchema, Socket as SocketModel } from './models/sockets.model';
import { Chatting, ChattingSchema } from './models/chattings.model';
import { RoomChatsService } from './chats.service';

@Module({
imports: [
Expand All @@ -12,6 +12,6 @@ import { SocketSchema, Socket as SocketModel } from './models/sockets.model';
{ name: SocketModel.name, schema: SocketSchema },
]),
],
providers: [ChatsGateway, ChatsService],
providers: [ChatsGateway, RoomChatsService],
})
export class ChatsModule {}
28 changes: 14 additions & 14 deletions src/chats/chats.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ChatsService } from './chats.service';
// import { Test, TestingModule } from '@nestjs/testing';
// import { ChatsService } from './chats.service';

describe('ChatsService', () => {
let service: ChatsService;
// describe('ChatsService', () => {
// let service: ChatsService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ChatsService],
}).compile();
// beforeEach(async () => {
// const module: TestingModule = await Test.createTestingModule({
// providers: [ChatsService],
// }).compile();

service = module.get<ChatsService>(ChatsService);
});
// service = module.get<ChatsService>(ChatsService);
// });

it('should be defined', () => {
expect(service).toBeDefined();
});
});
// it('should be defined', () => {
// expect(service).toBeDefined();
// });
// });
Loading

0 comments on commit 72bb4eb

Please sign in to comment.