Skip to content

Commit

Permalink
save chat messages in db and show on reload
Browse files Browse the repository at this point in the history
  • Loading branch information
Porhay committed Jun 3, 2024
1 parent 736b608 commit f39af91
Show file tree
Hide file tree
Showing 22 changed files with 173 additions and 10 deletions.
9 changes: 9 additions & 0 deletions apps/shelter-client/src/api/requests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,12 @@ export const getUserProducts = async (userId: string | undefined) => {
console.log(`Error while getting user products, userId:${userId}`, error);
}
};

export const getChatMessages = async (lobbyId: string | undefined | null) => {
try {
const res = await gatewayHost.get(`/api/lobbies/${lobbyId}/chat-messages/`);
return res.data;
} catch (error) {
console.log(`Error while getting chat messages, lobbyId:${lobbyId}`, error);
}
};
12 changes: 12 additions & 0 deletions apps/shelter-client/src/components/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { handleKeyDown } from '../helpers';
import useSocketManager from '../hooks/useSocketManager';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMaximize } from '@fortawesome/free-solid-svg-icons';
import { getChatMessages } from '../api/requests';
import { useParams } from 'react-router-dom';

interface IState {
messages: Message[];
Expand All @@ -30,6 +32,7 @@ const Chat: FC = () => {
const { sm } = useSocketManager();
const user = useSelector((state: RootState) => state.user);
const lobby = useSelector((state: RootState) => state.lobby);
const { roomId } = useParams();
const chatRef = useRef<HTMLDivElement>(null);
const messageTextRef = useRef<HTMLDivElement>(null);
const resizeRef = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -59,6 +62,15 @@ const Chat: FC = () => {
}
}, [state.messages]);

// set chat messages on mount/reload
useEffect(() => {
const setData = async () => {
const chatMessages = await getChatMessages(roomId);
updateState({ messages: chatMessages });
};
setData();
}, []);

// FUNCTIONS
const handleSendMessage = () => {
if (state.newMessage.trim() !== '') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ChatMessagesController } from './chat-messages.controller';
import { ChatMessagesService } from './chat-messages.service';

describe('ChatMessagesController', () => {
let controller: ChatMessagesController;

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

controller = module.get<ChatMessagesController>(ChatMessagesController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
12 changes: 12 additions & 0 deletions apps/shelter-gateway/src/chat-messages/chat-messages.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Controller, Get, Param } from '@nestjs/common';
import { ChatMessagesService } from './chat-messages.service';

@Controller('lobbies/:lobbyId/chat-messages')
export class ChatMessagesController {
constructor(private readonly chatMessagesService: ChatMessagesService) {}

@Get('')
getAllByLobbyId(@Param('lobbyId') lobbyId: string) {
return this.chatMessagesService.getAllByLobbyId(lobbyId);
}
}
11 changes: 11 additions & 0 deletions apps/shelter-gateway/src/chat-messages/chat-messages.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { ChatMessagesService } from './chat-messages.service';
import { ChatMessagesController } from './chat-messages.controller';
import { DatabaseModule } from '@app/common';

@Module({
imports: [DatabaseModule],
controllers: [ChatMessagesController],
providers: [ChatMessagesService],
})
export class ChatMessagesModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ChatMessagesService } from './chat-messages.service';

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

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

service = module.get<ChatMessagesService>(ChatMessagesService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
46 changes: 46 additions & 0 deletions apps/shelter-gateway/src/chat-messages/chat-messages.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { DatabaseService, constants } from '@app/common';
import { Injectable } from '@nestjs/common';

@Injectable()
export class ChatMessagesService {
constructor(private readonly databaseService: DatabaseService) {}

// TODO: add caching
async getAllByLobbyId(lobbyId: string) {
const messages = // id, userId, lobbyId, text, mentionId, replyTo, created_at, updated_at
await this.databaseService.getChatMessagesByLobbyId(lobbyId);

// to avoid useless db calls
const userMap: { [userId: string]: any } = {};

const res: any[] = [];
for (const m of messages) {
if (!userMap[m.userId]) {
let user: any = await this.databaseService.getUserByIdOrNull(m.userId);
// means that user is bot
if (user) {
userMap[user.id] = user;
} else {
user = constants.allBots.find((bot) => bot.userId === m.userId);
userMap[user.userId] = user;
}
}
const message = {
sender: userMap[m.userId].displayName,
senderId: m.userId,
message: m.text,
avatar: userMap[m.userId].avatar,
timeSent: parseTimeStr(m.createdAt),
};
res.push(message);
}
return res; // return in chat message format
}
}

function parseTimeStr(date: Date) {
const hour = date.getHours().toString().padStart(2, '0');
const minute = date.getMinutes().toString().padStart(2, '0');
const timeStr = `${hour}:${minute}`;
return timeStr;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class CreateChatMessageDto {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateChatMessageDto } from './create-chat-message.dto';

export class UpdateChatMessageDto extends PartialType(CreateChatMessageDto) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class ChatMessage {}
2 changes: 1 addition & 1 deletion apps/shelter-gateway/src/game/game.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { SocketExceptions } from './utils/SocketExceptions';
import { LobbyCreateDto } from './dto/LobbyCreate';
import { LobbyJoinDto } from './dto/LobbyJoin';
import { ChatMessage } from './dto/ChatMessage';
import { ActivityLogsService } from '../activityLogs/activity-logs.service';
import { ActivityLogsService } from '../activity-logs/activity-logs.service';
import { isset, getTime, getRandomGreeting, getRandomIndex } from 'helpers';
import { constants } from '@app/common';

Expand Down
2 changes: 1 addition & 1 deletion apps/shelter-gateway/src/game/game.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
// import { GameGateway } from './game.gateway';
import { LobbyManager } from './lobby/lobby.manager';
import { DatabaseModule } from '@app/common';
import { ActivityLogsModule } from '../activityLogs/activity-logs.module';
import { ActivityLogsModule } from '../activity-logs/activity-logs.module';

@Module({
imports: [ActivityLogsModule],
Expand Down
9 changes: 7 additions & 2 deletions apps/shelter-gateway/src/game/instance/instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,9 +441,14 @@ export class Instance {
currentBot,
});
}
} else {
const messageContext: CreateChatMessageDto = {
userId: data.senderId,
lobbyId: this.lobbyId,
text: data.message,
}
await this.lobby.databaseService.createChatMessage(messageContext)
}

// await this.lobby.databaseService.createChatMessage(messageContext)
}

/* check if user revealed all possible characteristics and
Expand Down
2 changes: 1 addition & 1 deletion apps/shelter-gateway/src/game/lobby/lobby.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ServerEvents } from '../utils/ServerEvents';
import { ServerPayloads } from '../utils/ServerPayloads';
import { generateSixSymbolHash } from 'helpers';
import { AIService, DatabaseService } from '@app/common';
import { ActivityLogsService } from '../../activityLogs/activity-logs.service';
import { ActivityLogsService } from '../../activity-logs/activity-logs.service';

export class Lobby {
public readonly id: string = generateSixSymbolHash();
Expand Down
6 changes: 4 additions & 2 deletions apps/shelter-gateway/src/gateway.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import { GameModule } from './game/game.module';
import { ScheduleModule } from '@nestjs/schedule';
import { LobbyManager } from './game/lobby/lobby.manager';
import { LobbiesModule } from './lobbies/lobbies.module';
import { ActivityLogsModule } from './activityLogs/activity-logs.module';
import { ActivityLogsModule } from './activity-logs/activity-logs.module';
import { ActivityLogsService } from './activity-logs/activity-logs.service';
import { ChatMessagesModule } from './chat-messages/chat-messages.module';
import config from 'config';
import { ActivityLogsService } from './activityLogs/activity-logs.service';

@Module({
imports: [
Expand All @@ -19,6 +20,7 @@ import { ActivityLogsService } from './activityLogs/activity-logs.service';
GameModule,
LobbiesModule,
ActivityLogsModule,
ChatMessagesModule,

DatabaseModule,
FirebaseModule,
Expand Down
5 changes: 3 additions & 2 deletions libs/common/src/ai/ai.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,9 @@ export class AIService {
currentBot: any;
messageObj: any;
}) {
const lobbyMessages =
(await this.databaseService.getChatMessagesByLobbyId(data.lobbyId)) || [];
const lobbyMessages = await this.databaseService.getChatMessagesByLobbyId(
data.lobbyId,
);

// parse messages for OpenAI lib
const prevBotRelatedMessages: { role: string; content: string }[] = [];
Expand Down
2 changes: 1 addition & 1 deletion libs/common/src/database/database.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ export class DatabaseService {
where: { lobbyId: lobbyId },
});
if (!messages || messages.length === 0) {
return null;
return [];
}
return messages;
}
Expand Down
20 changes: 20 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mapped-types": "^2.0.5",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.3.3",
"@nestjs/platform-socket.io": "^10.3.3",
Expand Down

0 comments on commit f39af91

Please sign in to comment.