Skip to content

Commit

Permalink
feat: 修改 ws 在链接时认证。
Browse files Browse the repository at this point in the history
  • Loading branch information
Evansy committed Jul 16, 2023
1 parent 8eb46a4 commit 7374c51
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 16 deletions.
26 changes: 11 additions & 15 deletions src/utils/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useUserStore } from '@/stores/user'
import { useChatStore } from '@/stores/chat'
import { useGroupStore } from '@/stores/group'
import { useCachedStore } from '@/stores/cached'
import { WsResponseMessageType, WsRequestMsgType } from './wsType'
import { WsResponseMessageType } from './wsType'
import type {
LoginSuccessResType,
LoginInitResType,
Expand All @@ -22,14 +22,14 @@ class WS {
#connectReady = false

constructor() {
worker.postMessage('{"type":"initWS"}')
this.initConnect()
// 收到消息
worker.addEventListener('message', this.onWorkerMsg)

// 后台重试次数达到上限之后,tab 获取焦点再重试
document.addEventListener('visibilitychange', () => {
if (!document.hidden && !this.#connectReady) {
worker.postMessage('{"type":"initWS"}')
this.initConnect()
}

// 获得焦点停止消息闪烁
Expand All @@ -39,6 +39,11 @@ class WS {
})
}

initConnect = () => {
const token = localStorage.getItem('TOKEN')
worker.postMessage(`{"type":"initWS","value":${token ? `"${token}"` : null}}`)
}

onWorkerMsg = (e: MessageEvent<any>) => {
const params: { type: string; value: unknown } = JSON.parse(e.data)
switch (params.type) {
Expand All @@ -63,21 +68,10 @@ class WS {
this.#connectReady = false
}

// 检测登录状态
#detectionLoginStatus = () => {
const token = localStorage.getItem('TOKEN')
if (token) {
this.send({ type: WsRequestMsgType.Authorization, data: { token } })
// 获取用户详情
const userStore = useUserStore()
userStore.getUserDetailAction()
}
}

#dealTasks = () => {
this.#connectReady = true
// 先探测登录态
this.#detectionLoginStatus()
// this.#detectionLoginStatus()

setTimeout(() => {
const userStore = useUserStore()
Expand Down Expand Up @@ -140,6 +134,8 @@ class WS {
userStore.userInfo = { ...userStore.userInfo, ...rest }
localStorage.setItem('USER_INFO', JSON.stringify(rest))
localStorage.setItem('TOKEN', token)
// 获取用户详情
userStore.getUserDetailAction()
// 更新一下请求里面的 token.
computedToken.clear()
computedToken.get()
Expand Down
6 changes: 5 additions & 1 deletion src/utils/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ let reconnectCount = 0
let timer: null | number = null
// 重连🔐
let lockReconnect = false
// 重连🔐
let token: null | string = null

// 往 ws 发消息
const connectionSend = (value: object) => {
Expand Down Expand Up @@ -73,6 +75,7 @@ const onConnectError = () => {
// ws 连接 close
const onConnectClose = () => {
onCloseHandler()
token = null
postMsg({ type: 'close' })
}
// ws 连接成功
Expand All @@ -92,7 +95,7 @@ const initConnection = () => {
connection?.removeEventListener('error', onConnectError)
// 建立链接
// 本地配置到 .env 里面修改。生产配置在 .env.production 里面
connection = new WebSocket(import.meta.env.VITE_WS_URL)
connection = new WebSocket(`${import.meta.env.VITE_WS_URL}${token ? `?token=${token}` : ''}`)
// 收到消息
connection.addEventListener('message', onConnectMsg)
// 建立链接
Expand All @@ -108,6 +111,7 @@ self.onmessage = (e: MessageEvent<string>) => {
switch (type) {
case 'initWS': {
reconnectCount = 0
token = value
initConnection()
break
}
Expand Down

0 comments on commit 7374c51

Please sign in to comment.