73 lines
1.9 KiB
JavaScript
73 lines
1.9 KiB
JavaScript
import { Server } from 'socket.io';
|
|
import BaseService from '../services/BaseService.js';
|
|
|
|
const baseService = new BaseService();
|
|
|
|
let io;
|
|
const userSockets = {};
|
|
|
|
export function setupWebSocket(server) {
|
|
io = new Server(server, {
|
|
cors: {
|
|
origin: '*',
|
|
},
|
|
});
|
|
|
|
io.on('connection', (socket) => {
|
|
socket.on('setUserId', (userId) => {
|
|
if (userId) {
|
|
socket.userId = userId;
|
|
userSockets[userId] = socket.id;
|
|
}
|
|
});
|
|
socket.on('disconnect', () => {
|
|
if (socket.userId) {
|
|
delete userSockets[socket.userId];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
export function getIo() {
|
|
if (!io) {
|
|
throw new Error('Socket.io ist nicht initialisiert!');
|
|
}
|
|
return io;
|
|
}
|
|
|
|
export function getUserSockets() {
|
|
return userSockets;
|
|
}
|
|
|
|
export async function notifyUser(recipientHashedUserId, event, data) {
|
|
const io = getIo();
|
|
const userSockets = getUserSockets();
|
|
|
|
try {
|
|
const recipientUser = await baseService.getUserByHashedId(recipientHashedUserId);
|
|
if (recipientUser) {
|
|
const socketId = userSockets[recipientUser.hashedId];
|
|
if (socketId) {
|
|
io.to(socketId).emit(event, data);
|
|
}
|
|
} else {
|
|
console.log(`Benutzer mit gehashter ID ${recipientHashedUserId} nicht gefunden.`);
|
|
}
|
|
} catch (err) {
|
|
console.error('Fehler beim Senden der Benachrichtigung:', err);
|
|
}
|
|
}
|
|
|
|
export async function notifyAllUsers(event, data) {
|
|
const io = getIo();
|
|
const userSockets = getUserSockets();
|
|
|
|
try {
|
|
for (const [userId, socketId] of Object.entries(userSockets)) {
|
|
io.to(socketId).emit(event, data);
|
|
console.log(`Benachrichtigung an Benutzer mit ID ${userId} gesendet.`);
|
|
}
|
|
} catch (err) {
|
|
console.error('Fehler beim Senden der Benachrichtigung an alle Benutzer:', err);
|
|
}
|
|
} |