feat(frontend): add api client and socket client wrappers with runtime config
This commit is contained in:
36
src/lib/socket-client.ts
Normal file
36
src/lib/socket-client.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { io, Socket } from 'socket.io-client'
|
||||
import { getRuntimeConfig } from './runtime-config'
|
||||
|
||||
let socket: Socket | null = null
|
||||
|
||||
export function getSocketClient(userId = 'frontend-user'): Socket {
|
||||
if (socket) return socket
|
||||
|
||||
const cfg = getRuntimeConfig()
|
||||
socket = io(cfg.guildSocketBase, {
|
||||
transports: ['websocket'],
|
||||
auth: {
|
||||
apiKey: cfg.apiKey,
|
||||
userId,
|
||||
},
|
||||
autoConnect: false,
|
||||
})
|
||||
|
||||
return socket
|
||||
}
|
||||
|
||||
export function reconnectSocket(): Socket {
|
||||
if (socket) {
|
||||
socket.disconnect()
|
||||
socket = null
|
||||
}
|
||||
const next = getSocketClient()
|
||||
next.connect()
|
||||
return next
|
||||
}
|
||||
|
||||
export function disconnectSocket(): void {
|
||||
if (!socket) return
|
||||
socket.disconnect()
|
||||
socket = null
|
||||
}
|
||||
Reference in New Issue
Block a user