-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
161 lines (140 loc) · 4.55 KB
/
Copy pathserver.js
File metadata and controls
161 lines (140 loc) · 4.55 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
// server.js - Custom Next.js server with Socket.io
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const { Server } = require("socket.io");
const mongoose = require("mongoose");
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = parseInt(process.env.PORT || "3000", 10);
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
// MongoDB connection
const connectDB = async () => {
if (mongoose.connections[0].readyState) {
return;
}
try {
await mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB connected for Socket.io server");
} catch (error) {
console.error("MongoDB connection error:", error);
}
};
app.prepare().then(() => {
const httpServer = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url, true);
await handle(req, res, parsedUrl);
} catch (err) {
console.error("Error handling request:", err);
res.statusCode = 500;
res.end("Internal server error");
}
});
const io = new Server(httpServer, {
cors: {
origin: process.env.NEXTAUTH_URL || `http://localhost:${port}`,
methods: ["GET", "POST"],
},
});
// Socket.io connection handling
io.on("connection", (socket) => {
console.log("Client connected:", socket.id);
// Join conversation room
socket.on("join_conversation", (conversationId) => {
socket.join(conversationId);
console.log(`Socket ${socket.id} joined conversation ${conversationId}`);
});
// Leave conversation room
socket.on("leave_conversation", (conversationId) => {
socket.leave(conversationId);
console.log(`Socket ${socket.id} left conversation ${conversationId}`);
});
// Handle new message
socket.on("send_message", async (data) => {
try {
await connectDB();
// Import models dynamically
const Message = require("./src/models/Message").default;
const Conversation = require("./src/models/Conversation").default;
// Save message to database
const message = new Message({
conversationId: data.conversationId,
senderId: data.senderId,
senderName: data.senderName,
content: data.content,
});
await message.save();
// Update conversation's last message
await Conversation.findByIdAndUpdate(data.conversationId, {
lastMessage: data.content,
lastMessageAt: new Date(),
});
// Emit message to all users in the conversation room
io.to(data.conversationId).emit("receive_message", {
_id: message._id,
conversationId: message.conversationId,
senderId: message.senderId,
senderName: message.senderName,
content: message.content,
createdAt: message.createdAt,
read: message.read,
});
} catch (error) {
console.error("Error sending message:", error);
socket.emit("message_error", { error: "Failed to send message" });
}
});
// Handle typing indicator
socket.on("typing", (data) => {
socket.to(data.conversationId).emit("user_typing", {
conversationId: data.conversationId,
userId: data.userId,
userName: data.userName,
});
});
// Handle stop typing
socket.on("stop_typing", (data) => {
socket.to(data.conversationId).emit("user_stop_typing", {
conversationId: data.conversationId,
userId: data.userId,
});
});
// Mark messages as read
socket.on("mark_as_read", async (data) => {
try {
await connectDB();
const Message = require("./src/models/Message").default;
await Message.updateMany(
{
conversationId: data.conversationId,
senderId: { $ne: data.userId },
read: false,
},
{ read: true }
);
socket.to(data.conversationId).emit("messages_read", {
conversationId: data.conversationId,
readBy: data.userId,
});
} catch (error) {
console.error("Error marking messages as read:", error);
}
});
socket.on("disconnect", () => {
console.log("Client disconnected:", socket.id);
});
});
httpServer
.once("error", (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
});