Enhance WebSocket support and update environment configuration

- Added VITE_SOCKET_URL to docker-compose.yml for WebSocket connection.
- Updated update-docker-env.sh to handle SSL options for WebSocket URLs.
- Modified Dockerfile to include VITE_SOCKET_URL in env-config.js.
- Implemented getSocketUrl function in frontend to retrieve WebSocket URL.
- Refactored socket configuration to use centralized socket URL from environment settings.
This commit is contained in:
chamiakJ
2025-04-28 11:43:16 +05:30
parent 2a3ae31e4e
commit 6e4bdea1c2
6 changed files with 65 additions and 10 deletions

View File

@@ -9,7 +9,8 @@ RUN npm ci
COPY . .
# Create env-config.js dynamically during build
RUN echo "window.VITE_API_URL='${VITE_API_URL:-http://backend:3000}';" > ./public/env-config.js
RUN echo "window.VITE_API_URL='${VITE_API_URL:-http://backend:3000}';" > ./public/env-config.js && \
echo "window.VITE_SOCKET_URL='${VITE_SOCKET_URL:-ws://backend:3000}';" >> ./public/env-config.js
RUN npm run build
@@ -27,6 +28,7 @@ RUN echo '#!/bin/sh\n\
# Update env-config.js with runtime environment variables\n\
cat > /app/build/env-config.js << EOL\n\
window.VITE_API_URL="${VITE_API_URL:-http://backend:3000}";\n\
window.VITE_SOCKET_URL="${VITE_SOCKET_URL:-ws://backend:3000}";\n\
EOL\n\
exec serve -s build -l 5000' > /app/start.sh && \
chmod +x /app/start.sh

View File

@@ -1,13 +1,14 @@
/**
* Environment configuration
* Reads from window.VITE_API_URL (set by env-config.js)
* Falls back to import.meta.env.VITE_API_URL (set during build time)
* Falls back to a development default
* Reads from window environment variables (set by env-config.js)
* Falls back to import.meta.env variables (set during build time)
* Falls back to development defaults
*/
declare global {
interface Window {
VITE_API_URL?: string;
VITE_SOCKET_URL?: string;
}
}
@@ -26,6 +27,30 @@ export const getApiUrl = (): string => {
return 'http://localhost:3000';
};
export const getSocketUrl = (): string => {
// First check runtime-injected environment variables
if (window.VITE_SOCKET_URL) {
return window.VITE_SOCKET_URL;
}
// Then check build-time environment variables
if (import.meta.env.VITE_SOCKET_URL) {
return import.meta.env.VITE_SOCKET_URL;
}
// Default based on API URL (convert http->ws or https->wss)
const apiUrl = getApiUrl();
if (apiUrl.startsWith('https://')) {
return apiUrl.replace('https://', 'wss://');
} else if (apiUrl.startsWith('http://')) {
return apiUrl.replace('http://', 'ws://');
}
// Final fallback
return 'ws://localhost:3000';
};
export default {
apiUrl: getApiUrl(),
socketUrl: getSocketUrl(),
};

View File

@@ -1,5 +1,7 @@
import config from '@/config/env';
export const SOCKET_CONFIG = {
url: import.meta.env.VITE_SOCKET_URL || 'ws://localhost:3000',
url: config.socketUrl,
options: {
transports: ['websocket'],
path: '/socket',