feat: add new file
This commit is contained in:
30
src/api/websocket.ts
Normal file
30
src/api/websocket.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
type Handler = (data: unknown) => void
|
||||
|
||||
let ws: WebSocket | null = null
|
||||
let handler: Handler | null = null
|
||||
|
||||
function getUrl(): string {
|
||||
return `${window.location.origin.replace(/^http/, 'ws')}/ws`
|
||||
}
|
||||
|
||||
export function connectSituationWebSocket(onData: Handler): () => void {
|
||||
handler = onData
|
||||
if (ws?.readyState === WebSocket.OPEN) return () => {}
|
||||
|
||||
ws = new WebSocket(getUrl())
|
||||
ws.onmessage = (e) => {
|
||||
try {
|
||||
const msg = JSON.parse(e.data)
|
||||
if (msg.type === 'situation' && msg.data) handler?.(msg.data)
|
||||
} catch (_) {}
|
||||
}
|
||||
ws.onclose = () => {
|
||||
ws = null
|
||||
setTimeout(() => handler && connectSituationWebSocket(handler), 3000)
|
||||
}
|
||||
return () => {
|
||||
handler = null
|
||||
ws?.close()
|
||||
ws = null
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user