-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (56 loc) · 1.78 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
65
66
67
68
69
70
71
72
73
const express = require("express");
const chats = require("./data/data");
const dotenv = require("dotenv");
const colors = require('colors')
const cors = require("cors");
const connectDB = require("./configs/db");
const userRoutes = require("./routes/userRoutes");
const chatRoutes = require("./routes/chatRoutes");
const messageRoutes = require("./routes/messageRoutes")
const { notFound, errorHandler } = require("./middleware/errorMiddleware");
const app = express();
app.use(cors());
app.use(express.json());
dotenv.config();
connectDB();
// end points
app.use('/api/user', userRoutes);
app.use('/api/chat', chatRoutes);
app.use('/api/message', messageRoutes);
app.use(notFound);
app.use(errorHandler);
const PORT = process.env.PORT || 8000;
const server = app.listen(
PORT,
console.log(`Server running on PORT ${PORT}...`.yellow.bold)
);
const io = require("socket.io")(server, {
cors: {
origin: '*'
},
});
io.on("connection", (socket) => {
console.log("Connected to socket.io");
socket.on("setup", (userData) => {
socket.join(userData._id);
socket.emit("connected");
});
socket.on("join chat", (room) => {
socket.join(room);
console.log("User Joined Room: " + 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", (newMessageRecieved) => {
var chat = newMessageRecieved.chat;
if (!chat.users) return console.log("chat.users not defined");
chat.users.forEach((user) => {
if (user._id == newMessageRecieved.sender._id) return;
socket.in(user._id).emit("message recieved", newMessageRecieved);
});
});
socket.off("setup", () => {
console.log("USER DISCONNECTED");
socket.leave(userData._id);
});
});