-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
77 lines (53 loc) · 1.77 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
require('./config/config');
require('./db/mongoose.js');
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const moment = require('moment');
const socketIO = require('socket.io');
var { User } = require('./models/user');
var { Event } = require('./models/event');
var app = express();
var userRoute = require('./routes/user.route');
var eventRoute = require('./routes/event.route');
var server = http.createServer(app);
var io = socketIO(server);
const port = process.env.PORT;
var date = moment();
app.use(bodyParser.json());
app.use(express.static('./public'));
io.on('connection', (socket) => {
let token;
socket.on('auth', async (data, callback) => {
try {
const user = await User.findByToken(data.token);
if (!user) {
return callback('Authentication failed')
}
token = data.token;
const event = await Event.findByRoomKey(data.room);
if (!event) {
return callback('No such room.')
}
if (moment(event.time).format('YYYYMMDD') < date.format('YYYYMMDD')) {
console.log('Event already over');
return callback('Event already over')
}
if(!event.members.some((member) => member.equals(user._id))){
return callback('User not in event.');
}
socket.join(data.room);
var count = io.sockets.adapter.rooms[data.room].length
console.log(`${count}/${event.members.length} online.`);
io.to(data.room).emit('testPrint', `${count}/${event.members.length} online.`)
} catch (e) {
callback(e);
}
});
});
app.use('/users', userRoute);
app.use('/events', eventRoute);
server.listen(port, () => {
console.log(`Started on port ${port}`);
});
module.exports = { app }