-
Notifications
You must be signed in to change notification settings - Fork 0
/
socketio.js
63 lines (57 loc) · 1.68 KB
/
socketio.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
let onlineUsers = [];
module.exports = (io, myDataBase, chatDB) => {
io.on("connection", (socket) => {
let name = socket.request.user.name;
let username = socket.request.user.username;
let img = socket.request.user.avatar;
socket.join(username);
chatDB.findOne({ pair: [username, username] }, (err, doc) => {
if (!doc) chatDB.insertOne({ pair: [username, username], message: [] });
});
onlineUsers.push({ username, avatar: img, name });
io.emit("user", {
name,
username,
onlineUsers,
connected: true,
});
socket.on("chat-message", (message) => {
io.in(message.recipant).emit("chat-message", message);
chatDB.findOne(
{ pair: { $all: [message.recipant, message.sender] } },
(err, doc) => {
if (doc) {
chatDB.updateOne(doc, {
$push: {
message: {
message: message.message,
sender: message.sender,
time: message.time,
},
},
});
} else {
chatDB.insertOne({
pair: [message.recipant, message.sender],
message: [
{
message: message.message,
sender: message.sender,
time: message.time,
},
],
});
}
}
);
});
socket.on("disconnect", () => {
onlineUsers = onlineUsers.filter((e) => e.username !== username);
io.emit("user", {
name,
username,
connected: false,
});
});
});
};