Skip to content

Commit

Permalink
πŸ› fix: λ ˆλ””μŠ€ μ €μž₯둜직 μžμ • μ•Œλ¦Ό μ΄λ²€νŠΈμ—λ„ μΆ”κ°€
Browse files Browse the repository at this point in the history
  • Loading branch information
asn6878 committed Dec 4, 2024
1 parent 45d0e4b commit b536497
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions server/src/chat/chat.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ const CHAT_HISTORY_LIMIT = 20;
const CHAT_MIDNIGHT_CLIENT_NAME = 'system';
const MAX_CLIENTS = 500;

type BroadcastPayload = {
username: string;
message: string;
timestamp: Date;
};

@Injectable()
@WebSocketGateway({
cors: {
Expand Down Expand Up @@ -45,12 +51,15 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
});
}

private emitMidnightMessage() {
const broadcastPayload = {
private async emitMidnightMessage() {
const broadcastPayload: BroadcastPayload = {
username: CHAT_MIDNIGHT_CLIENT_NAME,
message: '',
timestamp: new Date(),
};

await this.saveMessageToRedis(broadcastPayload);

this.server.emit('message', broadcastPayload);
}

Expand Down Expand Up @@ -93,23 +102,15 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
const redisKey = CLIENT_KEY_PREFIX + ip;
const clientName = await this.redisService.redisClient.get(redisKey);

const broadcastPayload = {
const broadcastPayload: BroadcastPayload = {
username: clientName,
message: payload.message,
timestamp: new Date(),
};
this.server.emit('message', broadcastPayload);

await this.redisService.redisClient.lpush(
CHAT_HISTORY_KEY,
JSON.stringify(broadcastPayload),
);
await this.saveMessageToRedis(broadcastPayload);

await this.redisService.redisClient.ltrim(
CHAT_HISTORY_KEY,
0,
CHAT_HISTORY_LIMIT - 1,
);
this.server.emit('message', broadcastPayload);
}

private getIp(client: Socket) {
Expand All @@ -123,7 +124,7 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {

private async getOrSetClientNameByIp(ip: string) {
const redisKey = CLIENT_KEY_PREFIX + ip;
let clientName = await this.redisService.redisClient.get(redisKey);
let clientName: string = await this.redisService.redisClient.get(redisKey);

if (clientName) {
return clientName;
Expand All @@ -144,4 +145,17 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {

return getRandomNickname(type);
}

private async saveMessageToRedis(payload: BroadcastPayload) {
await this.redisService.redisClient.lpush(
CHAT_HISTORY_KEY,
JSON.stringify(payload),
);

await this.redisService.redisClient.ltrim(
CHAT_HISTORY_KEY,
0,
CHAT_HISTORY_LIMIT - 1,
);
}
}

0 comments on commit b536497

Please sign in to comment.