Init
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import {defineStore} from 'pinia';
|
||||
|
||||
type GatewayStatus = 'disconnected' | 'connecting' | 'connected' | 'error'
|
||||
|
||||
export const useGatewayStore = defineStore('gateway', {
|
||||
state: () => ({
|
||||
socket: null as WebSocket | null,
|
||||
status: 'disconnected' as GatewayStatus,
|
||||
reconnectAttempts: 0,
|
||||
}),
|
||||
|
||||
actions: {
|
||||
async connect() {
|
||||
if (this.socket && this.status === 'connected') {
|
||||
return
|
||||
}
|
||||
|
||||
this.status = 'connecting'
|
||||
|
||||
const wsUrl = `ws://localhost:3000/ws`
|
||||
const socket = new WebSocket(wsUrl)
|
||||
|
||||
socket.onopen = () => {
|
||||
this.status = 'connected'
|
||||
this.reconnectAttempts = 0
|
||||
}
|
||||
|
||||
socket.onclose = () => {
|
||||
this.status = 'disconnected'
|
||||
this.socket = null
|
||||
this.scheduleReconnect()
|
||||
}
|
||||
|
||||
socket.onerror = () => {
|
||||
this.status = 'error'
|
||||
}
|
||||
|
||||
socket.onmessage = event => {
|
||||
this.handleMessage(event.data)
|
||||
}
|
||||
|
||||
this.socket = socket
|
||||
},
|
||||
|
||||
async disconnect() {
|
||||
this.socket?.close()
|
||||
this.socket = null
|
||||
this.status = 'disconnected'
|
||||
},
|
||||
|
||||
async send(payload: object) {
|
||||
if (!this.socket || this.status !== 'connected') {
|
||||
console.warn('WebSocket is not connected')
|
||||
return
|
||||
}
|
||||
|
||||
this.socket.send(JSON.stringify(payload))
|
||||
},
|
||||
|
||||
async handleMessage(rawData: string) {
|
||||
},
|
||||
|
||||
async scheduleReconnect() {
|
||||
const delay = Math.min(1000 * 2 ** this.reconnectAttempts, 30000)
|
||||
this.reconnectAttempts += 1
|
||||
|
||||
window.setTimeout(() => {
|
||||
this.connect()
|
||||
}, delay)
|
||||
},
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user