-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
67 lines (55 loc) · 1.78 KB
/
socket.js
File metadata and controls
67 lines (55 loc) · 1.78 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
const socketIo = require("socket.io");
const messageSchema = require("./models/messageSchema");
const userSchema = require("./models/userSchema");
function socketConnection(server) {
const io = socketIo(server);
io.on("connection", async (socket) => {
const messages = await messageSchema.find({});
socket.on("chat message", async (data) => {
console.log("Sent Message:", data);
try {
const newMessage = new messageSchema({
user: data.user,
message: data.message,
});
await newMessage.save();
io.emit("chat message", { user: data.user, message: data.message });
} catch (error) {
console.error("Message saving error:", error);
}
});
io.to(socket.id).emit('old_messages', messages);
socket.on("register user", async (data) => {
try {
const existingUser = await userSchema.findOne({
$or: [{ email: data.email }, { username: data.username }],
});
if (existingUser) {
console.log("This email or username is already in use!");
io.emit(
"register user error",
"This email or username is already in use!"
);
return;
}
const newUser = new userSchema({
email: data.email,
username: data.username,
password: data.password,
});
await newUser.save();
io.emit("register user", {
email: data.email,
username: data.username,
password: data.password,
});
io.emit("register successful", "User created.");
console.log("Registered User:", data);
} catch (error) {
console.error("Register error:", error);
}
});
});
return io;
}
module.exports = socketConnection;