|
| 1 | +import { Server as SocketIOServer } from 'socket.io'; |
| 2 | +import { Server as HTTPServer } from 'http'; |
| 3 | +import { verifyToken } from '@clerk/express'; |
| 4 | + |
| 5 | +let io: SocketIOServer | null = null; |
| 6 | + |
| 7 | +/** |
| 8 | + * Call this function in server.ts after creating the HTTP server |
| 9 | + */ |
| 10 | +export const initializeSocket = (httpServer: HTTPServer): SocketIOServer => { |
| 11 | + io = new SocketIOServer(httpServer, { |
| 12 | + cors: { |
| 13 | + origin: process.env.FRONTEND_URL || 'http://localhost:5173', |
| 14 | + methods: ['GET', 'POST'], |
| 15 | + credentials: true, |
| 16 | + }, |
| 17 | + }); |
| 18 | + |
| 19 | + io.use(async (socket, next) => { |
| 20 | + try { |
| 21 | + const token = socket.handshake.auth.token; |
| 22 | + |
| 23 | + if (!token) { |
| 24 | + return next(new Error('Authentication token required')); |
| 25 | + } |
| 26 | + |
| 27 | + // Verify Clerk token |
| 28 | + const verified = await verifyToken(token, { |
| 29 | + secretKey: process.env.CLERK_SECRET_KEY!, |
| 30 | + clockSkewInMs: 5000, |
| 31 | + }); |
| 32 | + |
| 33 | + if (!verified) { |
| 34 | + return next(new Error('Invalid authentication token')); |
| 35 | + } |
| 36 | + |
| 37 | + socket.data.userId = verified.sub; |
| 38 | + socket.data.sessionId = verified.sid; |
| 39 | + |
| 40 | + next(); |
| 41 | + } catch (error) { |
| 42 | + console.error('Socket authentication error:', error); |
| 43 | + next(new Error('Authentication failed')); |
| 44 | + } |
| 45 | + }); |
| 46 | + |
| 47 | + io.on('connection', (socket) => { |
| 48 | + console.log(`User connected: ${socket.data.userId} (Socket: ${socket.id})`); |
| 49 | + |
| 50 | + socket.on('disconnect', () => { |
| 51 | + console.log(`User disconnected: ${socket.data.userId} (Socket: ${socket.id})`); |
| 52 | + }); |
| 53 | + |
| 54 | + // Uncomment and implement these handlers as needed |
| 55 | + |
| 56 | + /* |
| 57 | + // Join a conversation room |
| 58 | + socket.on('join_conversation', (data: { conversationId: string }) => { |
| 59 | + socket.join(`conversation:${data.conversationId}`); |
| 60 | + console.log(`User ${socket.data.userId} joined conversation ${data.conversationId}`); |
| 61 | + }); |
| 62 | +
|
| 63 | + // Leave a conversation room |
| 64 | + socket.on('leave_conversation', (data: { conversationId: string }) => { |
| 65 | + socket.leave(`conversation:${data.conversationId}`); |
| 66 | + console.log(`User ${socket.data.userId} left conversation ${data.conversationId}`); |
| 67 | + }); |
| 68 | +
|
| 69 | + // Send message event (you'll also save to DB in the controller) |
| 70 | + socket.on('send_message', async (data: { conversationId: string; content: string }) => { |
| 71 | + try { |
| 72 | + // Verify user is part of this conversation (check DB) |
| 73 | + // Save message to database via controller |
| 74 | + // Then emit to all users in the conversation room |
| 75 | + io?.to(`conversation:${data.conversationId}`).emit('new_message', { |
| 76 | + conversationId: data.conversationId, |
| 77 | + message: { |
| 78 | + // message data from DB |
| 79 | + } |
| 80 | + }); |
| 81 | + } catch (error) { |
| 82 | + socket.emit('error', { message: 'Failed to send message' }); |
| 83 | + } |
| 84 | + }); |
| 85 | +
|
| 86 | + // Mark messages as read |
| 87 | + socket.on('mark_as_read', async (data: { conversationId: string }) => { |
| 88 | + try { |
| 89 | + // Update DB to mark messages as read |
| 90 | + // Emit to conversation room |
| 91 | + io?.to(`conversation:${data.conversationId}`).emit('messages_read', { |
| 92 | + conversationId: data.conversationId, |
| 93 | + userId: socket.data.userId, |
| 94 | + readAt: new Date().toISOString() |
| 95 | + }); |
| 96 | + } catch (error) { |
| 97 | + socket.emit('error', { message: 'Failed to mark as read' }); |
| 98 | + } |
| 99 | + }); |
| 100 | + */ |
| 101 | + }); |
| 102 | + |
| 103 | + return io; |
| 104 | +}; |
| 105 | + |
| 106 | +export const getSocketIO = (): SocketIOServer => { |
| 107 | + if (!io) { |
| 108 | + throw new Error('Socket.IO not initialized. Call initializeSocket() first.'); |
| 109 | + } |
| 110 | + return io; |
| 111 | +}; |
| 112 | + |
| 113 | +export const emitToConversation = ( |
| 114 | + conversationId: string, |
| 115 | + event: string, |
| 116 | + data: any |
| 117 | +): void => { |
| 118 | + if (io) { |
| 119 | + io.to(`conversation:${conversationId}`).emit(event, data); |
| 120 | + } |
| 121 | +}; |
| 122 | + |
| 123 | + |
| 124 | +export const emitToUser = (userId: string, event: string, data: any): void => { |
| 125 | + // Implement userId -> socketId mapping |
| 126 | + // You can store this mapping when users connect |
| 127 | + // For now, this is a placeholder |
| 128 | + console.warn('emitToUser not fully implemented. Needs userId -> socketId mapping.'); |
| 129 | +}; |
0 commit comments