refactor(websocket): 完善 WebSocket 客户端 token 处理和错误日志

- 在 WebSocketClient 构造函数中存储 token
- 自动在连接参数中添加 token
- 添加 WebSocket 消息解析错误的控制台日志
This commit is contained in:
xingyy 2025-03-02 13:23:45 +08:00
parent 5d814a3922
commit e0af9f99a0

View File

@ -1,9 +1,11 @@
export class WebSocketClient { export class WebSocketClient {
private socket: WebSocket | null = null private socket: WebSocket | null = null
private baseUrl: string private baseUrl: string
private token: string
constructor(baseUrl: string, token: string) { constructor(baseUrl: string, token: string) {
this.baseUrl = baseUrl this.baseUrl = baseUrl
this.token = token
} }
connect(path: string, params: Record<string, any> = {}) { connect(path: string, params: Record<string, any> = {}) {
@ -12,6 +14,7 @@ export class WebSocketClient {
// 构建参数对象,自动添加 token // 构建参数对象,自动添加 token
const queryParams = { const queryParams = {
token: this.token,
...params ...params
} }
@ -30,11 +33,13 @@ export class WebSocketClient {
}, },
onMessage: (callback: (data: any) => void) => { onMessage: (callback: (data: any) => void) => {
this.socket!.onmessage = (event) => { this.socket!.onmessage = (event) => {
try { try {
const data = JSON.parse(event.data) const data = JSON.parse(event.data)
callback(data) callback(data)
} catch (error) { } catch (error) {
console.error('解析消息失败:', error)
} }
} }
}, },