forked from darkcris1/svelte-chat-app-socket.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
64 lines (56 loc) · 2.17 KB
/
index.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
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http);
const path = require("path");
const { formatMsgObj } = require("./utils");
const { createUser, getUsersInRoom, removeUser } = require("./users");
const { ServeGrip } = require( '@fanoutio/serve-grip' );
app.use(express.static(path.join(__dirname, "client/public")));
const serveGrip = new ServeGrip(/* config */);
app.use(serveGrip);
const SERVER_NAME = "_BOT_";
io.on("connection", (socket) => {
socket.on("send-message", ({ room, ...rest }, callback) => {
// send the message to everyone in the room
const formattedUser = formatMsgObj(rest);
socket.broadcast.to(room).emit("server-message", formattedUser);
callback && callback(formattedUser);
});
function sendServerMessage(room, message) {
socket.broadcast.to(room).emit(
"server-message",
formatMsgObj({
username: SERVER_NAME,
message,
})
);
}
socket.on("join-room", (newUser, callback) => {
// Add the user to memory
const joinedUser = createUser(socket.id, newUser);
const { room, username } = joinedUser;
// Notify the client who joined the chat
socket.join(room);
sendServerMessage(room, `${username} joined the chat`);
socket.broadcast.to(room).emit("user-join", joinedUser); // Emit an event to pass the user object who join the chat
const roomUsers = getUsersInRoom(room);
callback(roomUsers, joinedUser);
});
function handleLeaveAndDisconnect() {
const user = removeUser(socket.id);
if (!user) return;
const { room, username } = user;
sendServerMessage(room, `${username} left the chat`);
socket.broadcast.to(room).emit("user-disconnect", user);
}
socket.on("disconnect", handleLeaveAndDisconnect);
socket.on("user-leave", handleLeaveAndDisconnect);
});
app.get("*", (req, res) => {
res.send("<h1> 404 </h1>");
});
const PORT = process.env.PORT || 3000;
http.listen(PORT, () => {
console.log(`listening on port ${PORT}`);
});