-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
70 lines (62 loc) · 1.57 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
const express = require('express')
const cors = require('cors')
const mongoose = require('mongoose')
const authRoutes = require('./server/routes/auth')
const messageRoutes = require('./server/routes/messages')
const app = express()
const socket = require('socket.io')
const path = require('path')
require('dotenv').config()
app.use(
cors({
origin: '*',
methods: '*',
})
)
app.use(express.json())
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('DB Connetion Successfull')
})
.catch((err) => {
console.log(err.message)
})
app.use('/api/auth', authRoutes)
app.use('/api/messages', messageRoutes)
// server frontend
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../client/build')))
app.get('*', (req, res) =>
res.sendFile(
path.resolve(__dirname, '../', 'client', 'build', 'index.html')
)
)
} else {
app.get('/', (req, res) => res.send('Please set to production'))
}
const server = app.listen(process.env.PORT, () =>
console.log(`Server started on ${process.env.PORT}`)
)
const io = socket(server, {
cors: {
origin: '*',
methods: '*',
},
})
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)
}
})
})