-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
109 lines (78 loc) · 2.39 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
94
95
96
97
98
99
100
101
102
103
import express from 'express'
const app = express();
import mongoose from 'mongoose'
import dotenv from 'dotenv'
import bodyParser from 'body-parser';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import AuthRoute from './routes/AuthRoute.js'
import PostRoute from './routes/PostRoute.js'
import ChatRoute from './routes/ChatRoute.js'
import { Server } from 'socket.io';
import http from 'http'
import path from "path";
const httpServer = http.createServer(app);
const io = new Server(httpServer, {
cors: {
origin: ["http://localhost:3000"],
}
})
let users = [];
const addUser = (userId, socketId) => {
!users.some((user) => user.userId == userId) &&
users.push({ userId, socketId });
}
const removeUser = (socketId) => {
users = users.filter((user) => user.socketId !== socketId)
}
const getUser = (receivedId) => {
return users.find(user => user.userId === receivedId);
}
io.on("connection", (socket) => {
console.log("connection is ready");
socket.on("addUser", (userId) => {
addUser(userId, socket.id);
io.emit('getUsers', users);
})
socket.on('sendMessage', ({ senderId, receivedId, text }) => {
const user = getUser(receivedId);
io.emit("getMessage", { senderId, text });
})
socket.on("typing",({me})=>{
let flag=true;
io.emit("userTyping",{flag,me});
})
socket.on('base64 file',(document)=>{
console.log(document);
io.emit('base64 file',document);
})
socket.on('join-room',(roomId,userId)=>{
socket.join(roomId);
socket.broadcast.emit('user-connected',userId)
})
socket.on("disconnect", (socket) => {
console.log("user left...")
removeUser(socket.id);
io.emit('getUsers', users);
})
})
app.use(cors());
app.use(bodyParser.json({ limit: "50mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
app.use(cookieParser())
app.use('/api/user', AuthRoute);
app.use('/api/post', PostRoute);
app.use('/api/chat', ChatRoute);
dotenv.config();
const PORT = process.env.PORT;
const connect = async () => {
await mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true });
httpServer.listen(PORT, () => {
console.log(`connection is establist with localhost:${PORT}`);
})
}
connect();
app.use(express.static(path.resolve(path.resolve(), 'client', 'build')));
app.get('/', (req, res) => {
res.sendFile(path.resolve(path.resolve() + '/client/build/index.html'))
})