-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
120 lines (79 loc) · 2.92 KB
/
server.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const path = require('path')
const Comments = require('./models/commentModel')
const feedbackRouter = require('./routes/feedback');
const app = express()
app.use(express.json())
app.use(cors())
const http = require('http').createServer(app)
const io = require('socket.io')(http)
let users = []
io.on('connection', socket => {
// console.log(socket.id + ' connected.')
socket.on('joinRoom', id => {
const user = {userId: socket.id, room: id}
const check = users.every(user => user.userId !== socket.id)
if(check){
users.push(user)
socket.join(user.room)
}else{
users.map(user => {
if(user.userId === socket.id){
if(user.room !== id){
socket.leave(user.room)
socket.join(id)
user.room = id
}
}
})
}
// console.log(users)
// console.log(socket.adapter.rooms)
})
socket.on('createComment', async msg => {
const {username, content, product_id, createdAt, rating, send} = msg
const newComment = new Comments({
username, content, product_id, createdAt, rating
})
if(send === 'replyComment'){
const {_id, username, content, product_id, createdAt, rating} = newComment
const comment = await Comments.findById(product_id)
if(comment){
comment.reply.push({_id, username, content, createdAt, rating})
await comment.save()
io.to(comment.product_id).emit('sendReplyCommentToClient', comment)
}
}else{
await newComment.save()
io.to(newComment.product_id).emit('sendCommentToClient', newComment)
}
})
socket.on('disconnect', () => {
// console.log(socket.id + ' disconnected.')
users = users.filter(user => user.userId !== socket.id)
})
})
app.use('/api', require('./routes/productRouter'))
app.use('/api', require('./routes/commentRouter'))
app.use('/feedbacks', feedbackRouter);
const URI = process.env.MONGODB_URL
mongoose.connect(URI, {
useNewUrlParser: true,
useUnifiedTopology: true
}, err => {
if(err) throw err;
console.log('Connected to mongodb')
})
if(process.env.NODE_ENV === 'production'){
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'))
})
}
const PORT = process.env.PORT || 8070
http.listen(PORT, () => {
console.log('Server is running on port', PORT)
})