76 lines
2.0 KiB
TypeScript
76 lines
2.0 KiB
TypeScript
import { io, Socket } from 'socket.io-client';
|
|
|
|
let socket: Socket | null = null;
|
|
|
|
/**
|
|
* Get the base URL for socket.io connection
|
|
* Uses VITE_BASE_URL if available, otherwise derives from VITE_API_BASE_URL
|
|
*/
|
|
export function getSocketBaseUrl(): string {
|
|
// Prefer VITE_BASE_URL (direct backend URL without /api/v1)
|
|
const baseUrl = import.meta.env.VITE_BASE_URL;
|
|
if (baseUrl) {
|
|
return baseUrl;
|
|
}
|
|
|
|
// Fallback: derive from VITE_API_BASE_URL by removing /api/v1
|
|
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
|
|
if (apiBaseUrl) {
|
|
return apiBaseUrl.replace(/\/api\/v1\/?$/, '');
|
|
}
|
|
|
|
// Development fallback
|
|
console.warn('[Socket] No VITE_BASE_URL or VITE_API_BASE_URL found, using localhost:5000');
|
|
return 'http://localhost:5000';
|
|
}
|
|
|
|
export function getSocket(baseUrl?: string): Socket {
|
|
// Use provided baseUrl or get from environment
|
|
const url = baseUrl || getSocketBaseUrl();
|
|
if (socket) return socket;
|
|
|
|
console.log('[Socket] Connecting to:', url);
|
|
|
|
socket = io(url, {
|
|
withCredentials: true,
|
|
transports: ['websocket', 'polling'],
|
|
path: '/socket.io',
|
|
reconnection: true,
|
|
reconnectionDelay: 1000,
|
|
reconnectionAttempts: 5
|
|
});
|
|
|
|
socket.on('connect', () => {
|
|
console.log('[Socket] Connected successfully:', socket?.id);
|
|
});
|
|
|
|
socket.on('connect_error', (error) => {
|
|
console.error('[Socket] Connection error:', error.message);
|
|
});
|
|
|
|
socket.on('disconnect', (reason) => {
|
|
console.log('[Socket] Disconnected:', reason);
|
|
});
|
|
|
|
return socket;
|
|
}
|
|
|
|
export function joinRequestRoom(socket: Socket, requestId: string, userId?: string) {
|
|
if (userId) {
|
|
socket.emit('join:request', { requestId, userId });
|
|
} else {
|
|
socket.emit('join:request', requestId);
|
|
}
|
|
}
|
|
|
|
export function leaveRequestRoom(socket: Socket, requestId: string) {
|
|
socket.emit('leave:request', requestId);
|
|
}
|
|
|
|
export function joinUserRoom(socket: Socket, userId: string) {
|
|
socket.emit('join:user', { userId });
|
|
console.log('[Socket] Joined personal notification room for user:', userId);
|
|
}
|
|
|
|
|