-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathchat.service.ts
More file actions
265 lines (236 loc) · 8.28 KB
/
chat.service.ts
File metadata and controls
265 lines (236 loc) · 8.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import { ForbiddenException, Inject, Injectable, Logger } from '@nestjs/common';
import { Repository } from 'typeorm';
import { ChatRoom } from "@schemas/chat-room.entity";
import { InjectRepository } from '@nestjs/typeorm';
import { ChatMessage } from "@schemas/chat-message.entity";
import { CustomerChatService } from './customer-chat.service';
import { DriverChatService } from './driver-chat.service';
import { BusinessChatService } from './business-chat.service';
import { ChatMessageDto, ChatRoomDto } from '../presentation/chat.dto';
import { UserDto, UserType } from "@auth/presentation/user.dto";
import { UserSocket } from '../presentation/chat.gateway';
import { CACHE_SERVICE, CacheService } from "@common/cache/cache.service";
import { DriverEntity } from "@schemas/drivers.entity";
import { CursorDto } from "@common/dto/cursor.dto";
import { BusinessEntity } from "@schemas/business.entity";
import { IChatService } from './chat.interface';
import { BadRequestException } from '@nestjs/common/exceptions';
import { Customer, ICustomer } from "@customer/customer.domain";
import { CustomerEntity } from "@schemas/customer.entity";
@Injectable()
export class ChatService {
private readonly logger = new Logger(ChatService.name);
private readonly roomServices = new Map<string, IChatService>();
constructor(
@InjectRepository(ChatRoom)
private readonly chatRepository: Repository<ChatRoom>,
@InjectRepository(ChatMessage)
private readonly chatMessageRepository: Repository<ChatMessage>,
@Inject(CACHE_SERVICE)
private readonly cacheService: CacheService,
private readonly driverChatService: DriverChatService,
private readonly customerChatService: CustomerChatService,
private readonly businessChatService: BusinessChatService,
) {
this.roomServices.set('driver', driverChatService);
this.roomServices.set('customer', customerChatService);
this.roomServices.set('business', businessChatService);
}
// 사용자 채팅방 목록
async findChatRooms(user: UserDto): Promise<ChatRoomDto[]> {
return await this.roomServices.get(user.userType!)!.findChatRooms(user);
}
// 유저가 채팅방에 존재하는지 확인
async exitsUserChatRoom(user: UserDto, chatRoomId: number): Promise<boolean> {
return this.roomServices
.get(user.userType!)!
.exitsUserRoom(user, chatRoomId);
}
// 채팅방 존재 유무
async exists(chatRoom: Partial<ChatRoom>): Promise<boolean> {
return this.chatRepository.exists({
where: {
chatRoomId: chatRoom.chatRoomId,
tsid: chatRoom.tsid,
},
});
}
// 특정 채팅방 조회
async findOne(chatRoom: Partial<ChatRoom>): Promise<ChatRoom> {
return await this.chatRepository.findOneOrFail({
where: {
chatRoomId: chatRoom.chatRoomId,
tsid: chatRoom.tsid,
},
});
}
async createChatRoom(
dto: ChatRoomDto,
customer: ICustomer,
): Promise<ChatRoomDto> {
if (dto.inviteUser.userId === customer.customerId) {
throw new BadRequestException('You cannot invite yourself');
}
const newRoom = await this.chatRepository.save(
this.chatRepository.create(dto),
);
dto.chatRoomId = newRoom.chatRoomId;
await this.roomServices.get(dto.inviteUser.userType!)!.createChatRoom(dto);
dto.inviteUser.userId = customer.customerId;
await this.customerChatService.createChatRoom(dto);
const roomDto = new ChatRoomDto();
roomDto.chatRoomId = newRoom.chatRoomId;
roomDto.tsid = newRoom.tsid;
roomDto.chatRoomName = newRoom.chatRoomName;
roomDto.inviteUser = dto.inviteUser;
roomDto.lastMessage = undefined;
roomDto.createdAt = newRoom.createdAt;
return roomDto;
}
async saveMessage(message: ChatMessageDto): Promise<ChatMessage> {
const lastMessage = await this.chatMessageRepository.find({
where: { chatRoomId: message.chatRoomId },
order: { chatMessageId: 'DESC' },
take: 1,
});
const lastMessageId: number = lastMessage[0]?.chatMessageId ?? 0;
return await this.chatMessageRepository.save(
this.chatMessageRepository.create({
chatMessageId: lastMessageId + 1,
chatRoomId: message.chatRoomId,
senderUuid: message.user.uuid,
chatMessageType: message.chatMessageType,
chatMessageContent: message.chatMessageContent,
}),
);
}
async findMessages(
chatRoomId: number,
cursor: CursorDto<ChatMessageDto>,
customer: Customer,
): Promise<CursorDto<ChatMessageDto>> {
const chatRoom = await this.customerChatService.exitsUserRoom(
{ userId: customer.customerId },
chatRoomId,
);
if (!chatRoom) {
throw new ForbiddenException('Your not allowed to access this room');
}
let query = this.chatMessageRepository
.createQueryBuilder('CM')
.leftJoinAndSelect('CM.chatRoom', 'chatRoom')
.leftJoinAndMapOne(
'CM.customer',
CustomerEntity,
'customer',
'CM.senderUuid = customer.uuid',
)
.leftJoinAndMapOne(
'CM.driver',
DriverEntity,
'driver',
'CM.senderUuid = driver.uuid',
)
.leftJoinAndMapOne(
'CM.business',
BusinessEntity,
'business',
'CM.senderUuid = business.uuid',
)
.where('CM.chatRoomId = :chatRoomId', { chatRoomId });
if (cursor.cursor) {
query = query.andWhere('CM.chatMessageId <= :cursor', {
cursor: cursor.cursor,
});
}
const chatMessages = await query
.orderBy('CM.chatMessageId', 'DESC')
.take(cursor.limit)
.getMany();
return {
data: chatMessages.map((message) => {
const userType: UserType = 'customer';
// todo: getRawMany로 변경해서 Type처리 제대로 할것
// @ts-ignore
const user = message[userType];
return {
chatRoomId: message.chatRoomId,
chatMessageId: message.chatMessageId,
senderUuid: message.senderUuid,
chatMessageType: message.chatMessageType,
chatMessageContent: message.chatMessageContent,
user: {
uuid: user.uuid,
userId: user[userType + 'Id'],
userType,
userName: user[userType + 'Name'],
},
};
}),
next: (chatMessages[chatMessages.length - 1]?.chatMessageId ?? 1) - 1,
};
}
// Socket Service
// 'join' message action
async join(client: UserSocket, chatRoomId: string): Promise<void> {
this.joinRoom(chatRoomId, client.user)
.then(() => {
return this.cacheService.sadd(
`chat:user:${client.user.uuid}:rooms`,
chatRoomId,
);
})
.then(() => {
!client.rooms.has(chatRoomId) && client.join(chatRoomId);
this.logger.log(`Client ${client.user.uuid} join room ${chatRoomId}`);
});
}
async joinRoom(chatRoomId: string, user: UserDto): Promise<boolean> {
await this.cacheService.sadd(`chat:room:${chatRoomId}:users`, user);
return true;
}
// 'exit' message action
async exit(client: UserSocket): Promise<void> {
// 인증실패시 로직 진행 X
if (!client.user) {
this.logger.debug('Client not authenticated');
return;
}
this.getUserChatRoomIds(client)
.then(async (chatRoomIds) => {
for (const chatRoomId of chatRoomIds) {
await this.exitRoom(chatRoomId, client.user);
}
return chatRoomIds;
})
.then((chatRoomIds) => {
this.cacheService
.del(`chat:user:${client.user.uuid}:rooms`)
.then(() => {
for (const chatRoomId of chatRoomIds) {
client.leave(chatRoomId);
}
});
});
}
async exitRoom(chatRoomId: string, user: UserDto): Promise<boolean> {
await this.cacheService
.srem(`chat:room:${chatRoomId}:users`, user)
.then((v) => this.logger.debug('Remove user count', v));
return true;
}
async getUserChatRoomIds(client: UserSocket): Promise<string[]> {
return await this.cacheService
.smembers(`chat:user:${client.user.uuid}:rooms`)
.then((v) => {
return v ?? [];
});
}
async getRoomUsers(chatRoomId: number): Promise<UserDto[]> {
return await this.cacheService
.smembersData<UserDto>(`chat:room:${chatRoomId}:users`)
.then((v) => {
return v ?? [];
});
}
}