提交 876dc993 作者: 方治民

feat: 新增 Stomp.connect token 有效性校验以及回调函数配置,添加 ping 消息示例

上级 59b6993b
......@@ -28,7 +28,9 @@
})
// test WebSocket(STOMP)
Stomp.connect()
Stomp.connect(() => {
Stomp.send('/app/ping', 'ping')
})
})
function surprise() {
......
......@@ -6,6 +6,7 @@ import type { RequestOptions, Result } from '/#/axios'
export interface CreateAxiosOptions extends AxiosRequestConfig {
authenticationScheme?: string
authenticationHeader?: string
transform?: AxiosTransform
requestOptions?: RequestOptions
}
......
......@@ -157,7 +157,7 @@ const transform: AxiosTransform = {
const token = userStore.getToken
if (token && (config as Recordable)?.requestOptions?.withToken !== false) {
// jwt token
;(config as Recordable).headers.Authorization = options.authenticationScheme
;(config as Recordable).headers[options.authenticationHeader] = options.authenticationScheme
? `${options.authenticationScheme} ${token}`
: token
}
......@@ -223,6 +223,8 @@ function createAxios(opt?: Partial<CreateAxiosOptions>) {
// authentication schemes,e.g: Bearer
// authenticationScheme: 'Bearer',
authenticationScheme: '',
// authenticationHeader: 'Authorization',
authenticationHeader: 'App-Token',
timeout: 10 * 1000,
// 基础接口地址
// baseURL: globSetting.apiUrl,
......
......@@ -76,18 +76,18 @@ class StompInstance {
/**
* 创建连接
*/
connect() {
async connect(cb?: () => void) {
// 如已存在连接则不创建
if (this.client && this.client.connected) {
return
}
// 检查登录是否有效
const available = await API.auth.valid.request()
// 从缓存中获取token
const useStore = useUserStoreWithOut()
const token = useStore.getToken
const options = token ? { token } : {}
// TODO: 检查 Token 是否有效
const options = token && available ? { token } : {}
// 创建 Stomp 实例
this.client = Stomp.client(this.url) as Client
......@@ -129,14 +129,17 @@ class StompInstance {
})
// 发送登录消息
if (token) {
this.send('/app/login', { token })
if (token && available) {
this.send('/app/login', token)
}
// 连接成功后触发回调
cb?.()
},
(_) => {
// 重连
this.reconnectId = setTimeout(() => {
this.reconnect()
this.reconnectId = setTimeout(async () => {
await this.reconnect()
}, this.reconnectInterval)
},
)
......@@ -145,7 +148,7 @@ class StompInstance {
/**
* 重新连接
*/
reconnect() {
async reconnect() {
// 停止重连事件
if (this.reconnectId) {
clearTimeout(this.reconnectId)
......@@ -163,7 +166,7 @@ class StompInstance {
})
// 连接
this.connect()
await this.connect()
}
/**
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论