-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
105 lines (84 loc) · 2.51 KB
/
server.js
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
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cors = require("cors");
const User = require("./models/User");
const formatMessage = require("./utils/messages.js");
const {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers,
} = require("./utils/users.js");
const router = require("./router");
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*", // Update with your frontend's domain if needed
methods: ["GET", "POST"],
},
});
app.use(cors());
app.use(router);
const botName = "ChatBot";
dotenv.config();
// Serve static files
app.use(express.static(path.join(__dirname, "public")));
// Connect to MongoDB
mongoose.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on("connected", () => console.log("MongoDB Connected"));
mongoose.connection.on("error", (err) =>
console.error("MongoDB Connection Error:", err)
);
io.on("connection", (socket) => {
console.log(`User connected: ${socket.id}`);
// Join a chat room
socket.on("joinRoom", async ({ username, room }) => {
console.log(socket.id, username, room);
const user = await userJoin(socket.id, username, room);
console.log("not here",user)
if (user) {
socket.join(user.room);
socket.emit("message", formatMessage(botName, "Welcome to the chat"));
socket.broadcast
.to(user.room)
.emit(
"message",
formatMessage(botName, `${user.username} has joined the chat`)
);
io.to(user.room).emit("roomUsers", {
room: user.room,
users: await getRoomUsers(user.room),
});
}
});
// Handle chat messages
socket.on("chatMessage", async (msg) => {
const user = await getCurrentUser(socket.id);
if (user) {
io.to(user.room).emit("message", formatMessage(user.username, msg));
}
});
// Handle disconnect event
socket.on("disconnect", async () => {
const user = await userLeave(socket.id);
if (user) {
io.to(user.room).emit(
"message",
formatMessage(botName, `${user.username} has left the chat`)
);
io.to(user.room).emit("roomUsers", {
room: user.room,
users: await getRoomUsers(user.room),
});
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));