Skip to content

Commit 456d8b1

Browse files
committed
Add websockets for chathistory
1 parent a47ed36 commit 456d8b1

File tree

5 files changed

+654
-280
lines changed

5 files changed

+654
-280
lines changed

collab-service/app/model/repository.js

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { connect } from 'mongoose';
1+
import { connect, mongoose } from 'mongoose';
22
import UsersSession from "./usersSession-model.js";
33

44
export async function connectToMongo() {
@@ -51,4 +51,55 @@ export async function get_all_rooms() {
5151
console.error('Error getting all rooms:', error);
5252
return null;
5353
}
54-
}
54+
}
55+
56+
57+
// Function to add a new message to chatHistory with transaction support
58+
export async function addMessageToChat(roomId, userId, text) {
59+
// Start a session for the transaction
60+
const session = await mongoose.startSession();
61+
62+
try {
63+
session.startTransaction();
64+
65+
// Find the session document by roomId within the transaction
66+
const sessionDoc = await UsersSession.findOne({ roomId }).session(session);
67+
68+
if (!sessionDoc) {
69+
throw new Error('Room not found');
70+
}
71+
72+
// Determine the next message index within the transaction
73+
const lastMessageIndex = sessionDoc.chatHistory.length > 0
74+
? sessionDoc.chatHistory[sessionDoc.chatHistory.length - 1].messageIndex
75+
: -1;
76+
77+
// Create the new message with incremented messageIndex
78+
const newMessage = {
79+
messageIndex: lastMessageIndex + 1,
80+
userId,
81+
text,
82+
timestamp: new Date()
83+
};
84+
85+
// Add the new message to chatHistory within the transaction
86+
sessionDoc.chatHistory.push(newMessage);
87+
88+
// Save the document within the transaction
89+
await sessionDoc.save({ session });
90+
91+
// Commit the transaction
92+
await session.commitTransaction();
93+
94+
// End the session and return the new message
95+
session.endSession();
96+
return newMessage;
97+
98+
} catch (error) {
99+
// If an error occurs, abort the transaction
100+
await session.abortTransaction();
101+
session.endSession();
102+
console.error('Error adding message to chat:', error);
103+
throw error;
104+
}
105+
}

collab-service/app/model/usersSession-model.js

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,27 @@ import mongoose from 'mongoose';
22

33
const Schema = mongoose.Schema;
44

5+
6+
const messageSchema = new Schema({
7+
messageIndex: {
8+
type: Number,
9+
required: true
10+
},
11+
userId: {
12+
type: String,
13+
required: true
14+
},
15+
text: {
16+
type: String,
17+
required: true
18+
},
19+
// timestamp: {
20+
// type: Date,
21+
// default: Date.now,
22+
// required: true
23+
// }
24+
});
25+
526
const usersSessionSchema = new Schema({
627
users: {
728
type: [String],
@@ -15,7 +36,11 @@ const usersSessionSchema = new Schema({
1536
type: Date,
1637
required: true,
1738
default: Date.now
18-
}
39+
},
40+
chatHistory: {
41+
type: [messageSchema],
42+
default: []
43+
}
1944
});
2045

2146
export default mongoose.model('UsersSession', usersSessionSchema);

collab-service/app/server.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,45 @@
11
import { connectToMongo } from "./model/repository.js";
22
import http from "http";
33
import index from "./index.js";
4+
import { Server } from "socket.io";
5+
import { addMessageToChat } from "./model/repository.js";
6+
47
const PORT = process.env.PORT || 5000;
58
const server = http.createServer(index);
69

10+
const io = new Server(server, {
11+
cors: {
12+
origin: "*", // Allow all origins; replace with specific origin if needed
13+
methods: ["GET", "POST"],
14+
allowedHeaders: ["Content-Type", "Authorization"],
15+
credentials: true
16+
}
17+
});
18+
19+
io.on('connection', (socket) => {
20+
console.log('User connected to Socket.IO');
21+
22+
// Join a room based on roomId
23+
socket.on('joinRoom', (roomId) => {
24+
socket.join(roomId);
25+
console.log(`User joined room: ${roomId}`);
26+
});
27+
28+
// Handle incoming chat messages
29+
socket.on('sendMessage', async (data) => {
30+
const { roomId, userId, text } = data;
31+
const newMessage = await addMessageToChat(roomId, userId, text);
32+
33+
// Broadcast the message to all clients in the same room
34+
io.to(roomId).emit('chatMessage', newMessage);
35+
});
36+
37+
socket.on('disconnect', () => {
38+
console.log('User disconnected from Socket.IO');
39+
});
40+
});
41+
42+
743
connectToMongo().then(() => {
844
server.listen(PORT, () => {
945
console.log(`Server running on http://localhost:${PORT}`);

0 commit comments

Comments
 (0)