index.ts 828 B

1234567891011121314151617181920212223
  1. import { urlJoin } from '@/lib/helper'
  2. import { useSettingsStore, useUserStore } from '@/pinia'
  3. import { storeToRefs } from 'pinia'
  4. import ReconnectingWebSocket from 'reconnecting-websocket'
  5. function ws(url: string, reconnect: boolean = true): ReconnectingWebSocket | WebSocket {
  6. const user = useUserStore()
  7. const settings = useSettingsStore()
  8. const { token } = storeToRefs(user)
  9. const protocol = location.protocol === 'https:' ? 'wss://' : 'ws://'
  10. const node_id = (settings.environment.id > 0) ? (`&x_node_id=${settings.environment.id}`) : ''
  11. const _url = urlJoin(protocol + window.location.host, window.location.pathname, url, `?token=${btoa(token.value)}`, node_id)
  12. if (reconnect)
  13. return new ReconnectingWebSocket(_url, undefined, { maxRetries: 10 })
  14. return new WebSocket(_url)
  15. }
  16. export default ws