-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (75 loc) · 2.17 KB
/
index.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
87
88
89
90
91
92
'use strict';
require('dotenv').config();
const { createServer } = require('http');
const { Server } = require('socket.io');
const registerUserHandlers = require('./handlers/userHandlers');
const PORT = 3000;
const httpServer = createServer();
const server = new Server(httpServer, {
cors: {
origin: '*',
},
});
httpServer.listen(PORT);
const onConnection = (socket) => {
console.log(`New user connected with ${socket.id}`);
socket.data = {
name: null,
room: null,
pass: null,
};
socket.on('disconnect', () => {
console.log(`User disconnected ${socket.id}`);
console.log(socket.data);
});
// EVENT LOGGING
socket.onAny((event, eventPayload = 'eventPayload null') => {
const eventNotification = {
event,
date: Date(),
eventPayload,
};
console.log(eventNotification); // Can swap for saved logs
});
// HANDLERS
registerUserHandlers(server, socket);
messageHandlers(server, socket);
};
server.on('connection', onConnection);
const messageHandlers = (server, socket) => {
// --- MESSAGE HANDLERS ---
const sendMessage = (message) => {
const newMessage = {
MID: `${socket.id}${Date.now()}`,
SID: socket.id,
message,
};
server.emit('MESSAGE:ADD', newMessage);
};
const deleteMessage = (MID) => {
server.emit('MESSAGE:DELETE', MID);
};
const messageReply = (originMID, message) => {
const replyMessage = {
originMID,
MID: `${socket.id}${Date.now()}`,
SID: socket.id,
message,
};
server.emit('MESSAGE:REPLY', replyMessage);
};
const messageReaction = (originMID, reaction) => {
const messageReaction = {
originMID,
MID: `${socket.id}${Date.now()}`, // can remove if one reaction per originMID
SID: socket.id,
reaction, // provided by the client, reference library kept in channel, send UID for any reaction to find reaction
};
server.emit('MESSAGE:REACTION', messageReaction);
};
// --- LISTENERS - USER:(EVENT_NAME) ---
socket.on('MESSAGE:ADD', sendMessage);
socket.on('MESSAGE:DELETE', deleteMessage);
socket.on('MESSAGE:REPLY', messageReply);
socket.on('MESSAGE:REACTION', messageReaction);
};