forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocketService.js
More file actions
57 lines (47 loc) · 1.41 KB
/
Copy pathsocketService.js
File metadata and controls
57 lines (47 loc) · 1.41 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
const { Server } = require('socket.io');
const { verifyToken } = require('./tokenService');
let io = null;
/**
* Initialise Socket.IO on the given HTTP server.
* Call once from server.js after creating the http.Server.
*/
function initSocketIO(httpServer, corsOptions) {
io = new Server(httpServer, {
cors: corsOptions,
path: '/socket.io',
});
// JWT handshake authentication
io.use((socket, next) => {
const token = socket.handshake.auth?.token;
if (!token) return next(new Error('Authentication required'));
try {
const decoded = verifyToken(token);
if (!decoded?.userId) return next(new Error('Invalid token'));
socket.userId = decoded.userId;
next();
} catch {
next(new Error('Invalid or expired token'));
}
});
io.on('connection', (socket) => {
// Each user joins their own private room so we can target them
socket.join(`user:${socket.userId}`);
socket.on('disconnect', () => {
socket.leave(`user:${socket.userId}`);
});
});
return io;
}
/**
* Emit a notification to a specific user.
* @param {number|string} userId
* @param {{ type: string, message: string, createdAt: string }} notification
*/
function emitNotification(userId, notification) {
if (!io) return;
io.to(`user:${userId}`).emit('notification', notification);
}
function getIO() {
return io;
}
module.exports = { initSocketIO, emitNotification, getIO };