feat: implement real-time chat with Socket.IO
Implemented WebSocket-based real-time messaging for both event rooms and private match chats using Socket.IO with comprehensive test coverage. Backend changes: - Installed socket.io@4.8.1 for WebSocket server - Created Socket.IO server with JWT authentication middleware - Implemented event room management (join/leave/messages) - Added active users tracking with real-time updates - Implemented private match room messaging - Integrated Socket.IO with Express HTTP server - Messages are persisted to PostgreSQL via Prisma - Added 12 comprehensive unit tests (89.13% coverage) Frontend changes: - Installed socket.io-client for WebSocket connections - Created socket service layer for connection management - Updated EventChatPage with real-time messaging - Updated MatchChatPage with real-time private chat - Added connection status indicators (● Connected/Disconnected) - Disabled message input when not connected Infrastructure: - Updated nginx config to proxy WebSocket connections at /socket.io - Added Upgrade and Connection headers for WebSocket support - Set long timeouts (7d) for persistent WebSocket connections Key features: - JWT-authenticated socket connections - Room-based architecture for events and matches - Real-time message broadcasting - Active users list with automatic updates - Automatic cleanup on disconnect - Message persistence in database Test coverage: - 12 tests passing (authentication, event rooms, match rooms, disconnect, errors) - Socket.IO module: 89.13% statements, 81.81% branches, 91.66% functions - Overall coverage: 81.19% Phase 1, Step 4 completed. Ready for Phase 2 (Core Features).
This commit is contained in:
@@ -2,15 +2,15 @@ import { useState, useRef, useEffect } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import Layout from '../components/layout/Layout';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { mockPrivateMessages } from '../mocks/messages';
|
||||
import { mockUsers } from '../mocks/users';
|
||||
import { Send, Video, Upload, X, Check, Link as LinkIcon } from 'lucide-react';
|
||||
import { connectSocket, getSocket } from '../services/socket';
|
||||
|
||||
const MatchChatPage = () => {
|
||||
const { matchId } = useParams();
|
||||
const { user } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [messages, setMessages] = useState(mockPrivateMessages);
|
||||
const [messages, setMessages] = useState([]);
|
||||
const [newMessage, setNewMessage] = useState('');
|
||||
const [selectedFile, setSelectedFile] = useState(null);
|
||||
const [isTransferring, setIsTransferring] = useState(false);
|
||||
@@ -18,10 +18,11 @@ const MatchChatPage = () => {
|
||||
const [webrtcStatus, setWebrtcStatus] = useState('disconnected'); // disconnected, connecting, connected, failed
|
||||
const [showLinkInput, setShowLinkInput] = useState(false);
|
||||
const [videoLink, setVideoLink] = useState('');
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const messagesEndRef = useRef(null);
|
||||
const fileInputRef = useRef(null);
|
||||
|
||||
// Partner user (mockup)
|
||||
// Partner user (mockup - TODO: fetch from backend in Phase 2)
|
||||
const partner = mockUsers[1]; // sarah_swing
|
||||
|
||||
const scrollToBottom = () => {
|
||||
@@ -32,21 +33,56 @@ const MatchChatPage = () => {
|
||||
scrollToBottom();
|
||||
}, [messages]);
|
||||
|
||||
useEffect(() => {
|
||||
// Connect to Socket.IO
|
||||
const socket = connectSocket();
|
||||
|
||||
if (!socket) {
|
||||
console.error('Failed to connect to socket');
|
||||
return;
|
||||
}
|
||||
|
||||
// Socket event listeners
|
||||
socket.on('connect', () => {
|
||||
setIsConnected(true);
|
||||
// Join match room
|
||||
socket.emit('join_match_room', { matchId: parseInt(matchId) });
|
||||
console.log(`Joined match room ${matchId}`);
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
setIsConnected(false);
|
||||
});
|
||||
|
||||
// Receive messages
|
||||
socket.on('match_message', (message) => {
|
||||
setMessages((prev) => [...prev, message]);
|
||||
});
|
||||
|
||||
// Cleanup
|
||||
return () => {
|
||||
socket.off('connect');
|
||||
socket.off('disconnect');
|
||||
socket.off('match_message');
|
||||
};
|
||||
}, [matchId, user.id]);
|
||||
|
||||
const handleSendMessage = (e) => {
|
||||
e.preventDefault();
|
||||
if (!newMessage.trim()) return;
|
||||
|
||||
const message = {
|
||||
id: messages.length + 1,
|
||||
room_id: 10,
|
||||
user_id: user.id,
|
||||
username: user.username,
|
||||
content: newMessage,
|
||||
type: 'text',
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
const socket = getSocket();
|
||||
if (!socket || !socket.connected) {
|
||||
alert('Not connected to chat server');
|
||||
return;
|
||||
}
|
||||
|
||||
// Send message via Socket.IO
|
||||
socket.emit('send_match_message', {
|
||||
matchId: parseInt(matchId),
|
||||
content: newMessage,
|
||||
});
|
||||
|
||||
setMessages([...messages, message]);
|
||||
setNewMessage('');
|
||||
};
|
||||
|
||||
@@ -204,8 +240,13 @@ const MatchChatPage = () => {
|
||||
<div className="flex flex-col h-[calc(100vh-320px)]">
|
||||
{/* Messages */}
|
||||
<div className="flex-1 overflow-y-auto p-4 space-y-4">
|
||||
{messages.length === 0 && (
|
||||
<div className="text-center text-gray-500 py-8">
|
||||
No messages yet. Start the conversation!
|
||||
</div>
|
||||
)}
|
||||
{messages.map((message) => {
|
||||
const isOwnMessage = message.user_id === user.id;
|
||||
const isOwnMessage = message.userId === user.id;
|
||||
return (
|
||||
<div
|
||||
key={message.id}
|
||||
@@ -213,7 +254,7 @@ const MatchChatPage = () => {
|
||||
>
|
||||
<div className={`flex items-start space-x-2 max-w-md ${isOwnMessage ? 'flex-row-reverse space-x-reverse' : ''}`}>
|
||||
<img
|
||||
src={isOwnMessage ? user.avatar : partner.avatar}
|
||||
src={message.avatar}
|
||||
alt={message.username}
|
||||
className="w-8 h-8 rounded-full"
|
||||
/>
|
||||
@@ -223,7 +264,7 @@ const MatchChatPage = () => {
|
||||
{message.username}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{new Date(message.created_at).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}
|
||||
{new Date(message.createdAt).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
@@ -376,11 +417,13 @@ const MatchChatPage = () => {
|
||||
value={newMessage}
|
||||
onChange={(e) => setNewMessage(e.target.value)}
|
||||
placeholder="Write a message..."
|
||||
className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500"
|
||||
disabled={!isConnected}
|
||||
className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500 disabled:opacity-50"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
|
||||
disabled={!isConnected}
|
||||
className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors disabled:opacity-50"
|
||||
>
|
||||
<Send className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
Reference in New Issue
Block a user