-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
86 lines (77 loc) · 2.55 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
const express = require("express");
const app = express();
const server = require("http").Server(app);
const io = require("socket.io")(server);
const next = require("next");
const connectDB = require("./db/connectDB");
const {
addUser,
removeUser,
findConnectedUser,
} = require("./server/userActions");
const {
loadMessages,
sendMsg,
setMessageToUnread,
deleteMsg,
} = require("./server/messageActions");
const dev = process.env.NODE_ENV !== "production";
dev && require("dotenv").config();
const nextApp = next({ dev });
const handle = nextApp.getRequestHandler();
const PORT = process.env.PORT || 8080;
app.use(express.json());
connectDB();
io.on("connection", (socket) => {
socket.on("join", async ({ userId }) => {
const users = await addUser(userId, socket.id);
setInterval(() => {
socket.emit("connectedUsers", {
users: users.filter((user) => user.userId !== userId),
});
}, 5000);
});
socket.on("loadMessages", async ({ userId, messagesWith }) => {
const { chat, error } = await loadMessages(userId, messagesWith);
if (!error) socket.emit("messagesLoaded", { chat });
else socket.emit("noChatFound");
});
socket.on("sendNewMsg", async ({ userId, msgSendToUserId, msg }) => {
const { newMsg, error } = await sendMsg(userId, msgSendToUserId, msg);
if (error) {
const sender = findConnectedUser(userId);
sender && io.to(sender.socketId).emit("msgNotSent");
return;
}
const receiver = findConnectedUser(msgSendToUserId);
if (receiver)
io.to(receiver.socketId).emit("newMsgReceived", { newMsg });
await setMessageToUnread(msgSendToUserId);
socket.emit("msgSent", { newMsg });
});
socket.on("deleteMsg", async ({ userId, messagesWith, msgId }) => {
const { success, error } = await deleteMsg(userId, messagesWith, msgId);
if (error) {
const user = findConnectedUser(userId);
user && io.to(user.socketId).emit("ErrorDeleteMsg");
return;
}
if (success) socket.emit("msgDeleted");
});
socket.on("disconnect", () => removeUser(socket.id));
});
nextApp.prepare().then(() => {
app.use("/api/signup", require("./api/signup"));
app.use("/api/auth", require("./api/login"));
app.use("/api/search", require("./api/search"));
app.use("/api/posts", require("./api/post"));
app.use("/api/profile", require("./api/profile"));
app.use("/api/notifications", require("./api/notifications"));
app.use("/api/chats", require("./api/chats"));
app.use("/api/reset", require("./api/reset"));
app.all("*", (req, res) => handle(req, res));
server.listen(PORT, (err) => {
if (err) throw err;
console.log("Server Started");
});
});