-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
50 lines (38 loc) · 1.03 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
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
app.use(express.static('public'))
const dbConnect = require('./db')
dbConnect()
const Comment = require('./models/comment')
app.use(express.json())
// Routes
app.post('/api/comments', (req, res) => {
const comment = new Comment({
username: req.body.username,
comment: req.body.comment
})
comment.save().then(response => {
res.send(response)
})
})
app.get('/api/comments', (req, res) => {
Comment.find().then(function(comments) {
res.send(comments)
})
})
const server = app.listen(port, () => {
console.log(`Listening on port ${port}`)
})
let io = require('socket.io')(server)
io.on('connection', (socket) => {
console.log(`New connection: ${socket.id}`)
// Recieve event
socket.on('comment', (data) => {
data.time = Date()
socket.broadcast.emit('comment', data)
})
socket.on('typing', (data) => {
socket.broadcast.emit('typing', data)
})
})