-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
103 lines (85 loc) · 2.45 KB
/
server.js
File metadata and controls
103 lines (85 loc) · 2.45 KB
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
'use strict';
const path = require('path');
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const UserService = require('./services/UserService');
const mongoose = require('mongoose');
const authRouter = require('./auth/authRouter');
const bodyParser = require('body-parser');
const formatMessage = require('./helpers/formatMessage');
const jsonParser = bodyParser.json();
const PORT = process.env.PORT || '3000';
const app = express();
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: `http://localhost:${PORT}`,
methods: ['GET', 'POST'],
transports: ['websocket', 'polling'],
credentials: true
},
allowEIO3: true
});
const userManager = new UserService();
//set static folder
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(jsonParser);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use('/auth', jsonParser, authRouter);
const botName = 'Messenger Bot';
// Run when client connects
io.on('connection', socket => {
const { id } = socket;
socket.on('joinRoom', ({ username, room }) => {
const user = userManager.addUser({ id, username, room });
socket.join(room);
// Broadcast when a user connects
socket.broadcast
.to(room)
.emit(
'message',
formatMessage(botName, `${user.username} has joined the chat`)
);
// Send users and room info
io.to(room).emit('roomUsers', {
room,
users: userManager.getRoomUsers(room)
});
});
// Listen for chatMessage
socket.on('chatMessage', msg => {
const user = userManager.getUser(id);
io.to(user.room).emit('message', formatMessage(user.username, msg));
});
// Runs when client disconnects
socket.on('disconnect', () => {
const user = userManager.removeUser(id);
if (user) {
const { room } = user;
io.to(room).emit(
'message',
formatMessage(botName, `${user.username} has left the chat`)
);
// Send users and room info
io.to(room).emit('roomUsers', {
room,
users: userManager.getRoomUsers(room)
});
}
});
});
const runServer = async () => {
try {
await mongoose.connect('mongodb+srv://ulu:ul67d3@cluster0.xnfaj.mongodb.net/messager?retryWrites=true&w=majority');
server.listen(PORT, () => console.log(`Server is running at ${PORT}`));
} catch (e) {
console.log(e);
}
};
runServer();