Enhance backend configuration and error handling: Update CORS settings to allow dynamic origins, improve RabbitMQ connection handling in chat services, and adjust API server host configuration. Refactor environment variables for better flexibility and add fallback mechanisms for WebSocket and chat services. Update frontend environment files for consistent API and WebSocket URLs.

This commit is contained in:
Torsten Schulz (local)
2026-03-18 22:45:22 +01:00
parent 59869e077e
commit 4442937ebd
29 changed files with 1226 additions and 396 deletions

View File

@@ -2,38 +2,59 @@
import { Server } from 'socket.io';
import amqp from 'amqplib/callback_api.js';
const RABBITMQ_URL = 'amqp://localhost';
const RABBITMQ_URL = process.env.AMQP_URL || 'amqp://localhost';
const QUEUE = 'chat_messages';
export function setupWebSocket(server) {
const io = new Server(server);
let channel = null;
amqp.connect(RABBITMQ_URL, (err, connection) => {
if (err) throw err;
if (err) {
console.warn(`[webSocketService] RabbitMQ nicht erreichbar (${RABBITMQ_URL}) - WebSocket läuft ohne Queue-Bridge.`);
return;
}
connection.createChannel((err, channel) => {
if (err) throw err;
connection.on('error', (connectionError) => {
console.warn('[webSocketService] RabbitMQ-Verbindung fehlerhaft:', connectionError.message);
channel = null;
});
connection.on('close', () => {
console.warn('[webSocketService] RabbitMQ-Verbindung geschlossen.');
channel = null;
});
connection.createChannel((channelError, createdChannel) => {
if (channelError) {
console.warn('[webSocketService] RabbitMQ-Channel konnte nicht erstellt werden:', channelError.message);
return;
}
channel = createdChannel;
channel.assertQueue(QUEUE, { durable: false });
channel.consume(QUEUE, (msg) => {
if (!msg) return;
const message = JSON.parse(msg.content.toString());
io.emit('newMessage', message);
}, { noAck: true });
});
});
io.on('connection', (socket) => {
console.log('Client connected via WebSocket');
io.on('connection', (socket) => {
console.log('Client connected via WebSocket');
// Konsumiert Nachrichten aus RabbitMQ und sendet sie an den WebSocket-Client
channel.consume(QUEUE, (msg) => {
const message = JSON.parse(msg.content.toString());
io.emit('newMessage', message); // Broadcast an alle Clients
}, { noAck: true });
socket.on('newMessage', (message) => {
if (channel) {
channel.sendToQueue(QUEUE, Buffer.from(JSON.stringify(message)));
return;
}
// Empfangt eine Nachricht vom WebSocket-Client und sendet sie an die RabbitMQ-Warteschlange
socket.on('newMessage', (message) => {
channel.sendToQueue(QUEUE, Buffer.from(JSON.stringify(message)));
});
io.emit('newMessage', message);
});
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
}