-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (43 loc) · 1.32 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
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const authRoutes = require("./routes/auth");
const messageRoutes = require("./routes/messages");
const socket = require("socket.io");
const connectDB = require("./models/db");
const http = require('http');
const app = express();
const server = http.createServer(app);
const io = socket(server, {
cors: {
origin: process.env.ALLOWED_ORIGIN,
credentials: true,
methods: ['GET', 'POST', 'PUT'],
allowedHeaders: ['Content-Type', 'Authorization']
},
});
const corsOptions = {
origin: process.env.ALLOWED_ORIGIN,
methods: ['GET', 'PUT', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization']
};
app.use(cors(corsOptions));
app.use(express.json());
// Connection to database
connectDB();
app.use("/api/auth", authRoutes);
app.use("/api/messages", messageRoutes);
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-recieve", data.msg);
}
});
});
server.listen(process.env.PORT, () => console.log('Server started at successfully!!!'));