-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathserver.js
110 lines (81 loc) · 2.37 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
106
107
108
109
110
import express from "express";
import dotenv from "dotenv";
dotenv.config();
import helmet from "helmet";
import xss from "xss-clean";
import mongoSanitize from "express-mongo-sanitize";
import morgan from "morgan";
import "express-async-errors";
import { createServer } from "http";
//socket
import { Server } from "socket.io";
//connect DB
import connectDB from "./db/connect.js";
import cors from "cors";
//middleware
import notFoundMiddleware from "./middleware/not-found.js";
import errorHandlerMiddleware from "./middleware/error-handler.js";
import authenticateUser from "./middleware/auth.js";
//routes
import authRoute from "./routes/auth.js";
import chatRoute from "./routes/chat.js";
import messageRoute from "./routes/message.js";
const app = express();
if (process.env.NODE_ENV !== "production") {
app.use(morgan("dev"));
}
app.use(express.json());
app.use(cors());
app.use(helmet());
app.use(xss());
app.use(mongoSanitize());
app.get("/", (req, res) => {
res.send("Server Running!");
});
app.use("/api/v1/auth", authRoute);
app.use("/api/v1/chat", authenticateUser, chatRoute);
app.use("/api/v1/message", authenticateUser, messageRoute);
app.use(notFoundMiddleware);
app.use(errorHandlerMiddleware);
const port = process.env.PORT || 5000;
const server = createServer(app);
const start = async () => {
try {
await connectDB(process.env.MONGO_URL);
server.listen(port, () =>
console.log(`Server Running on port : ${port}...`)
);
} catch (error) {
console.log(error);
}
};
start();
const io = new Server(server, {
pingTimeout: 60000,
cors: {
origin: "*",
},
});
io.on("connection", (socket) => {
//connected to correct id
socket.on("setup", (userData) => {
socket.join(userData._id);
socket.emit("connected");
});
socket.on("join-chat", (room) => {
socket.join(room);
});
socket.on("typing", (room) => socket.in(room).emit("typing"));
socket.on("stop-typing", (room) => socket.in(room).emit("stop-typing"));
socket.on("new-message", (newMessageReceived) => {
let chat = newMessageReceived.chat;
if (!chat.users) return console.log(`chat.users not defined`);
chat.users.forEach((user) => {
if (user._id === newMessageReceived.sender._id) return;
socket.in(user._id).emit("message-received", newMessageReceived);
});
});
socket.off("setup", () => {
socket.leave(userData._id);
});
});