-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
93 lines (74 loc) · 2.01 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config(); // load envirnment variable
const socket = require("socket.io");
const connectDb = require("./Database/ConnectDB");
const Router = require("./Route/auth");
const messageRoute = require("./Route/messageRoute");
const groupChat = require("./Route/groupChatRoute");
// Parse incomeing request
app.use(express.json());
// allow client to connect server
app.use(cors());
// connect Database
connectDb();
// default route
app.get((request, response) => {
response.status(200).json({ message: "API is rinning" });
});
// Routes
app.use(Router);
app.use(messageRoute);
app.use(groupChat);
const server = app.listen(8080);
// Socket io connection
const io = socket(server, {
cors: {
origin: "*",
credentials: true,
},
pingTimeOut: 6000,
});
const { addUser } = require("./Config/userGroup");
global.onlineUser = new Map();
const users = {};
const groups = {};
io.on("connection", (socket) => {
global.chatSocket = socket;
socket.on("add-user", (userId) => {
onlineUser.set(userId, socket.id);
users[userId] = socket.id;
console.log(users);
});
// group chat
socket.on("join", ({ group }) => {
groups[group] = socket.id;
socket.join(group);
socket.on("send-group-message", ({ message , group}) => {
io.to(groups[group]).emit("recive-group-message", {
group,
message,
});
});
});
socket.on("typing", (data) => {
socket.to(users[data.to]).emit("typing", data.to);
// console.log("typing" , data);
});
socket.on("group-message", (data) => {
console.log(data.groupId);
socket.emit(`recive-message`, data);
});
socket.on("send-message", (data) => {
const reciverId = users[data.to];
if (reciverId) {
socket.to(reciverId).emit("message-recive", data.message);
}
});
socket.on("disconnectServer", (userId) => {
console.log("...............");
delete users[userId];
console.log(users);
});
});