-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwsHandler.js
42 lines (35 loc) · 1001 Bytes
/
wsHandler.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
import { Server } from 'socket.io';
const wsHandler = (server) => {
const io = new Server(server, {
cors:true,
origins:["http://127.0.0.1:5347"]
});
return {
listen: () => listen(io)
};
};
const listen = (io) => {
io.use((socket, next) => {
const { id, email } = socket.handshake.auth;
if (!email) {
return next(new Error('invalid email'));
}
socket.user_id = id;
socket.email = email;
return next();
});
io.sockets.on('connection', (socket) => {
console.log(socket.email + ' joined');
socket.join(socket.email);
socket.on('private-message', ({to, message}) => {
io.sockets.in(to.email).emit('private-message-incoming', {
from: {
user_id: socket.user_id,
email: socket.email
},
message
});
});
});
}
export default wsHandler;