websocket use cookie connect

This commit is contained in:
hjlarry
2026-01-20 17:01:40 +08:00
parent bdac6f91dd
commit f99ac24d5c
3 changed files with 17 additions and 26 deletions

View File

@ -7,7 +7,7 @@ type MockSocket = {
}
type IoOptions = {
auth?: { token?: string }
auth?: unknown
path?: string
transports?: string[]
withCredentials?: boolean
@ -104,18 +104,15 @@ describe('WebSocketClient', () => {
expect(second).toBe(first)
})
it('attaches auth token from localStorage and emits user_connect on connect', async () => {
it('emits user_connect on connect without auth payload', async () => {
const mockSocket = createMockSocket('socket-auth')
ioMock.mockImplementation((url: string, options: IoOptions) => {
expect(options.auth).toEqual({ token: 'secret-token' })
expect(options.auth).toBeUndefined()
return mockSocket
})
setGlobalWindow({
location: { protocol: 'https:', host: 'example.com' },
localStorage: {
getItem: vi.fn(() => 'secret-token'),
},
} as unknown as typeof window)
const { WebSocketClient } = await import('../websocket-manager')

View File

@ -1,7 +1,6 @@
import type { Socket } from 'socket.io-client'
import type { DebugInfo, WebSocketConfig } from '../types/websocket'
import { io } from 'socket.io-client'
import { ACCESS_TOKEN_LOCAL_STORAGE_NAME } from '@/config'
type AckArgs = unknown[]
@ -82,24 +81,16 @@ export class WebSocketClient {
this.connecting.add(appId)
const authToken = typeof window === 'undefined'
? undefined
: window.localStorage.getItem(ACCESS_TOKEN_LOCAL_STORAGE_NAME) ?? undefined
const socketOptions: {
path: string
transports: WebSocketConfig['transports']
withCredentials?: boolean
auth?: { token: string }
} = {
path: '/socket.io',
transports: this.config.transports,
withCredentials: this.config.withCredentials,
}
if (authToken)
socketOptions.auth = { token: authToken }
const socket = io(this.config.url!, socketOptions)
this.connections.set(appId, socket)