-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
53 lines (39 loc) · 1.16 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
const express = require('express')
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const path = require('path');
const cors = require('cors')
const api = require('./api')
const db = require('./db')
const Chat = require('./api/Models/Chat');
app.use(express.json());
app.use(cors({
exposedHeaders: 'x-auth',
}));
app.use(express.static(path.join(__dirname, 'build')));
app.use('/api/', api)
io.on('connection', (socket) => {
console.log("New connection!");
socket.on("createMessage", (id, from, text) => {
Chat.findById(id).then(chat => {
chat.newMessage(from, text).then(message => {
io.to(id).emit("newMessage", message)
})
})
})
socket.on("joinRoom", (room) => {
console.log("Joining room: ", room)
socket.join(room);
})
socket.on('disconnect', () => {
console.log("User disconnected.")
})
})
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build/index.html'));
});
const port = process.env.PORT || 5000;
server.listen(port, () => {
console.log("Listen on port " + port)
})