-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocketControllers.js
87 lines (76 loc) · 2.34 KB
/
socketControllers.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
const Post = require('./models/post');
const Room = require('./models/room');
const async = require('async');
const socketioJwt = require('socketio-jwt');
const mongoose = require('mongoose');
function socketConnection(io){
io.on('connection', (socket) =>{
//When someone sends the post he also gets posts update with the new post
//TODO caching
socket.on('send post', (data) => {
const roomID = data.room.toString();
const post = new Post({
user: data.user._id,
body: data.body,
date: data.date,
room: roomID
});
//Saving post and sending back the update
async.series({
post: function(callback){
post.save(callback);
},
get: function(callback){
Post.find({room: data.room})
.populate('user')
.populate('room')
.exec(callback);
}
}, function(err, result){
if(!err){
const toSend = {
posts: result.get,
roomID: roomID
}
return io.to(roomID).emit('update posts', toSend);
}
return console.log(err);
});
});
socket.on('join rooms', (data) => {
console.log('joining rooms');
Room.find({
users: mongoose.Types.ObjectId(data._id)
})
.populate('users')
.then(rooms => {
rooms.forEach(room =>{
socket.join(room._id.toString());
});
}).catch(err => {
console.log(err);
})
});
});
}
function socketJwtVerification(io){
io.use(socketioJwt.authorize({
secret: process.env.JWT_SECRET,
handshake: true
}));
}
//Returns Null if there was an error
function a(user){
return Room.find({
users: mongoose.Types.ObjectId(user._id)
})
.populate('users')
.then(result => {
return result;
})
.catch(err =>{
console.log(err);
});
}
exports.socketConnection = socketConnection;
exports.socketJwtVerification = socketJwtVerification;