Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
82 lines (67 loc) · 3.32 KB
/
Copy pathserver.js
File metadata and controls
82 lines (67 loc) · 3.32 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
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
// server.js
const http = require('http');
const { Server } = require('socket.io');
const app = require('./src/app');
const messagesRepository = require('./src/features/messages/messages.repository'); // Import your messages repo
require('dotenv').config(); // Ensures environment variables load during network configuration
// Determine target execution port from .env environment file
const PORT = process.env.SERVER_PORT || 8080;
// 1. Wrap the Express app configuration inside a native Node.js HTTP Server
const server = http.createServer(app);
// 2. Attach Socket.io to the HTTP Server instance
const io = new Server(server, {
cors: {
origin: "*", // Crucial for allowing your Flutter app to connect across networks/emulators
methods: ["GET", "POST"]
}
});
// 3. Define the Real-Time Socket Connection Layer
io.on('connection', (socket) => {
console.log(`🔌 New client established socket lane: ${socket.id}`);
// Event A: When a user opens a chat screen in Flutter, they join that specific room ID channel
socket.on('join_room', (roomId) => {
socket.join(roomId);
console.log(`📁 Socket ${socket.id} joined room channel: ${roomId}`);
});
// Event B: When a user sends a live message payload down the pipeline
socket.on('send_message', async (messageData) => {
const { room_id, content, sender_name, sender_id } = messageData;
console.log(`✉️ Live message in room [${room_id}]: ${content}`);
try {
// 1. Asynchronously commit the incoming message directly to PostgreSQL
const savedMsg = await messagesRepository.saveMessage(room_id, sender_id, content);
console.log(`💾 Message securely saved to database. ID: ${savedMsg.id}`);
// 2. Instantly broadcast the production database object to EVERYONE listening inside that exact room channel
io.to(room_id).emit('receive_message', {
id: savedMsg.id, // Real database UUID/ID instead of math.random
room_id: savedMsg.room_id,
content: savedMsg.content,
sender_id: savedMsg.sender_id,
sender_name: sender_name, // Carry over the display name for frontend rendering convenience
sent_at: savedMsg.sent_at // Official database timestamp
});
} catch (error) {
console.error("❌ Failed to commit live message to database:", error.message);
// Let the sending socket client know things failed if they need a UI retry trigger
socket.emit('message_error', { error: "Message could not be saved to server history." });
}
});
// Event C: When a user exits the chat window or closes the app
socket.on('disconnect', () => {
console.log(`❌ Client snapped connection: ${socket.id}`);
});
});
// 4. FIX COMPLETE: We listen using 'server.listen' so BOTH Express routes and Sockets share port 8080!
server.listen(PORT, () => {
console.log(`🚀 Real-time engine and API gateway standing guard!`);
console.log(`📡 URL : http://localhost:${PORT}`);
});
// Global Crisis Listeners to log issues gracefully instead of failing silently
process.on('unhandledRejection', (reason, promise) => {
console.error('❌ CRITICAL UNHANDLED REJECTION AT:', promise, 'REASON:', reason);
});
process.on('uncaughtException', (error) => {
console.error(`❌ CRITICAL UNCAUGHT EXCEPTION: ${error.message}`);
console.error(error.stack);
process.exit(1);
});