Files
yourpart3/frontend/src/services/chatWs.js

44 lines
1.7 KiB
JavaScript
Executable File

import { getChatWsUrlFromEnv } from '@/utils/appConfig.js';
// Small helper to resolve the Chat WebSocket URL from env or sensible defaults
export function getChatWsUrl() {
// Prefer explicit env var
const override = (typeof window !== 'undefined' && window.localStorage) ? window.localStorage.getItem('chatWsOverride') : '';
if (override && typeof override === 'string' && override.trim()) {
return override.trim();
}
return getChatWsUrlFromEnv();
}
// Provide a list of candidate WS URLs to try, in order of likelihood.
export function getChatWsCandidates() {
const override = (typeof window !== 'undefined' && window.localStorage) ? window.localStorage.getItem('chatWsOverride') : '';
if (override && typeof override === 'string' && override.trim()) {
return [override.trim()];
}
const resolved = getChatWsUrlFromEnv();
return [resolved, `${resolved}/`];
}
// Return optional subprotocols for the WebSocket handshake.
export function getChatWsProtocols() {
try {
const ls = (typeof window !== 'undefined' && window.localStorage) ? window.localStorage.getItem('chatWsProtocols') : '';
if (ls && ls.trim()) {
// Accept JSON array or comma-separated
if (ls.trim().startsWith('[')) return JSON.parse(ls);
return ls.split(',').map(s => s.trim()).filter(Boolean);
}
} catch (_) {}
const env = import.meta?.env?.VITE_CHAT_WS_PROTOCOLS;
if (env && typeof env === 'string' && env.trim()) {
try {
if (env.trim().startsWith('[')) return JSON.parse(env);
} catch (_) {}
return env.split(',').map(s => s.trim()).filter(Boolean);
}
// Default to the 'chat' subprotocol so the server can gate connections accordingly
return ['chat'];
}