74 lines
1.9 KiB
JavaScript
74 lines
1.9 KiB
JavaScript
|
|
import { Server as SocketIOServer } from "socket.io";
|
||
|
|
|
||
|
|
/** @type {SocketIOServer | null} */
|
||
|
|
let io = null;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Initialize Socket.IO server
|
||
|
|
* @param {import('http').Server} httpServer
|
||
|
|
* @returns {SocketIOServer}
|
||
|
|
*/
|
||
|
|
export function initializeSocketIO(httpServer) {
|
||
|
|
if (io) {
|
||
|
|
console.log("Socket.IO already initialized");
|
||
|
|
return io;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Create Socket.IO server
|
||
|
|
io = new SocketIOServer(httpServer, {
|
||
|
|
// CORS only needed if clients connect from different origin
|
||
|
|
cors: process.env.NODE_ENV === "production" && process.env.APP_URL
|
||
|
|
? {
|
||
|
|
origin: process.env.APP_URL,
|
||
|
|
credentials: true,
|
||
|
|
}
|
||
|
|
: undefined, // No CORS in dev (same origin)
|
||
|
|
});
|
||
|
|
|
||
|
|
// Connection handling
|
||
|
|
io.on("connection", (socket) => {
|
||
|
|
console.log("Client connected:", socket.id);
|
||
|
|
|
||
|
|
// Join draft room
|
||
|
|
socket.on("join-draft", (seasonId) => {
|
||
|
|
if (!seasonId) {
|
||
|
|
console.error("No seasonId provided for join-draft");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
socket.join(`draft-${seasonId}`);
|
||
|
|
console.log(`Socket ${socket.id} joined draft-${seasonId}`);
|
||
|
|
});
|
||
|
|
|
||
|
|
// Leave draft room
|
||
|
|
socket.on("leave-draft", (seasonId) => {
|
||
|
|
if (!seasonId) return;
|
||
|
|
socket.leave(`draft-${seasonId}`);
|
||
|
|
console.log(`Socket ${socket.id} left draft-${seasonId}`);
|
||
|
|
});
|
||
|
|
|
||
|
|
socket.on("disconnect", () => {
|
||
|
|
console.log("Client disconnected:", socket.id);
|
||
|
|
});
|
||
|
|
});
|
||
|
|
|
||
|
|
// Store globally for access in route handlers
|
||
|
|
// This is safe because server.js controls the lifecycle
|
||
|
|
global.__socketIO = io;
|
||
|
|
|
||
|
|
console.log("Socket.IO initialized");
|
||
|
|
return io;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Get the Socket.IO server instance
|
||
|
|
* @returns {SocketIOServer}
|
||
|
|
*/
|
||
|
|
export function getSocketIO() {
|
||
|
|
// Check both local and global storage
|
||
|
|
const instance = io || global.__socketIO;
|
||
|
|
if (!instance) {
|
||
|
|
throw new Error("Socket.IO not initialized. Call initializeSocketIO first.");
|
||
|
|
}
|
||
|
|
return instance;
|
||
|
|
}
|