index.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { storeToRefs } from 'pinia'
  2. import ReconnectingWebSocket from 'reconnecting-websocket'
  3. import { urlJoin } from '@/lib/helper'
  4. import { useSettingsStore, useUserStore } from '@/pinia'
  5. /**
  6. * Build WebSocket URL based on environment
  7. */
  8. function buildWebSocketUrl(url: string, token: string, shortToken: string, nodeId?: number): string {
  9. const node_id = nodeId && nodeId > 0 ? `&x_node_id=${nodeId}` : ''
  10. // Use shortToken if available (without base64 encoding), otherwise use regular token (with base64 encoding)
  11. const authParam = shortToken ? `token=${shortToken}` : `token=${btoa(token)}`
  12. // In development mode, connect directly to backend server
  13. if (import.meta.env.DEV) {
  14. const proxyTarget = import.meta.env.VITE_PROXY_TARGET || 'http://localhost:9000'
  15. const wsTarget = proxyTarget.replace(/^https?:/, location.protocol === 'https:' ? 'wss:' : 'ws:')
  16. return urlJoin(wsTarget, url, `?${authParam}`, node_id)
  17. }
  18. // In production mode, use current host
  19. const protocol = location.protocol === 'https:' ? 'wss://' : 'ws://'
  20. return urlJoin(protocol + window.location.host, window.location.pathname, url, `?${authParam}`, node_id)
  21. }
  22. function ws(url: string, reconnect: boolean = true): ReconnectingWebSocket | WebSocket {
  23. const user = useUserStore()
  24. const settings = useSettingsStore()
  25. const { token, shortToken } = storeToRefs(user)
  26. const _url = buildWebSocketUrl(url, token.value, shortToken.value, settings.environment.id)
  27. if (reconnect)
  28. return new ReconnectingWebSocket(_url, undefined, { maxRetries: 10 })
  29. return new WebSocket(_url)
  30. }
  31. export default ws