-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (44 loc) · 1.35 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
const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const userRoutes = require("./routes/userRoutes");
const messageRoute = require("./routes/messagesRoute");
const socket = require("socket.io");
mongoose.set('strictQuery', true);
dotenv.config();
app.use(cors());
app.use(express.json());
app.use("/api/auth", userRoutes);
app.use("/api/message", messageRoute);
//mongoose connection
mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("DB Connection Successful!")
}).catch((err) => console.log(err));
const server = app.listen(process.env.PORT, ()=>{
console.log(`Server started on Port ${process.env.PORT}`);
});
const io = socket(server,{
cors: {
origin: process.env.ORIGIN,
credentials: true,
},
});
//store all online users inside this map
global.onlineUsers = new Map();
io.on("connection",(socket)=>{
global.chatSocket = socket;
socket.on("add-user",(userId)=>{
onlineUsers.set(userId,socket.id);
});
socket.on("send-msg",(data)=>{
const sendUserSocket = onlineUsers.get(data.to);
if(sendUserSocket) {
socket.to(sendUserSocket).emit("msg-recieved",data.message);
}
});
});