refactor(websocket): 重构 WebSocket 连接和管理

- 在 checkoutPage 中添加全局 WebSocket 客户端实例
- 移除 payment 中的 openRefreshResults 函数
- 更新 authStore,移除不再使用的 openRefreshResults
- 优化 WebSocketClient 类,移除冗余的 token 参数
- 在 nuxt.config.js 中添加 SSL 证书加载逻辑
This commit is contained in:
xingyy 2025-03-02 10:58:24 +08:00
parent b1d2dc19d2
commit 779dc84356
5 changed files with 23 additions and 33 deletions

View File

@ -45,8 +45,9 @@ const startPolling = () => {
setLoading(false) setLoading(false)
}, 180000)*/ }, 180000)*/
} }
let wsClient=null
const watchWebSocket = () => { const watchWebSocket = () => {
const wsClient = new WebSocketClient( wsClient = new WebSocketClient(
config.public.NUXT_PUBLIC_SOCKET_URL config.public.NUXT_PUBLIC_SOCKET_URL
) )
const ws = wsClient.connect('/api/v1/order/ws/v2', { const ws = wsClient.connect('/api/v1/order/ws/v2', {
@ -124,6 +125,7 @@ function setLoading(loading) {
onUnmounted(()=>{ onUnmounted(()=>{
wsClient.disconnect()
clearTimeout(timeoutTimer) clearTimeout(timeoutTimer)
clearInterval(pollTimer) clearInterval(pollTimer)

View File

@ -6,7 +6,7 @@ import { showLoadingToast ,closeToast} from 'vant';
import {authStore} from "~/stores/auth/index.js"; import {authStore} from "~/stores/auth/index.js";
import {message} from "~/components/x-message/useMessage.js"; import {message} from "~/components/x-message/useMessage.js";
const {checkoutSessionUrl,payment,payUid,openRefreshResults}= authStore() const {checkoutSessionUrl,payment,payUid}= authStore()
const payStatus=ref(0) const payStatus=ref(0)
definePageMeta({ definePageMeta({
i18n: 'payment.title' i18n: 'payment.title'
@ -48,7 +48,6 @@ const confirmPay=async ()=>{
checkoutSessionUrl.value=res.data.checkoutSessionUrl checkoutSessionUrl.value=res.data.checkoutSessionUrl
payUid.value=res.data.payUid payUid.value=res.data.payUid
openRefreshResults()
router.push('/checkoutPage') router.push('/checkoutPage')
} }
} }

View File

@ -18,27 +18,7 @@ export const authStore = createGlobalState(() => {
const router=useRouter() const router=useRouter()
const config = useRuntimeConfig() const config = useRuntimeConfig()
const payUid=useLocalStorage('payUid','') const payUid=useLocalStorage('payUid','')
const openRefreshResults=()=>{
const wsClient = new WebSocketClient(
config.public.NUXT_PUBLIC_SOCKET_URL,
token.value
)
const ws = wsClient.connect('/api/v1/order/ws',{
payUid:payUid.value
})
ws.onMessage((data) => {
console.log('openRefreshResults',data)
router.push({
path:'/payment/result',
query:{
orderNo:payUid.value
}
})
})
}
return{ return{
openRefreshResults,
payUid, payUid,
selectedZone, selectedZone,
payment, payment,

View File

@ -1,11 +1,9 @@
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> = {}) {
@ -14,7 +12,6 @@ export class WebSocketClient {
// 构建参数对象,自动添加 token // 构建参数对象,自动添加 token
const queryParams = { const queryParams = {
token: this.token,
...params ...params
} }
@ -33,7 +30,7 @@ export class WebSocketClient {
}, },
onMessage: (callback: (data: any) => void) => { onMessage: (callback: (data: any) => void) => {
this.socket!.onmessage = (event) => { this.socket!.onmessage = (event) => {
console.log('websocket收到消息', event)
try { try {
const data = JSON.parse(event.data) const data = JSON.parse(event.data)

View File

@ -12,6 +12,21 @@ const publicConfig = Object.entries(process.env)
return config return config
}, {}) }, {})
let httpsOptions = {}
try {
// 读取文件并转换为字符串
const key = fs.readFileSync(path.resolve(__dirname, 'ssl/localhost-key.pem'), 'utf-8')
const cert = fs.readFileSync(path.resolve(__dirname, 'ssl/localhost.pem'), 'utf-8')
httpsOptions = { key, cert }
console.log('SSL证书加载成功')
} catch (error) {
console.error('SSL证书加载失败:', error)
// 失败时使用HTTP
httpsOptions = false
}
export default defineNuxtConfig({ export default defineNuxtConfig({
modules: [ modules: [
'@vant/nuxt', '@vant/nuxt',
@ -138,11 +153,8 @@ export default defineNuxtConfig({
// 指定 Nuxt 应用程序的兼容性日期,确保应用程序在未来的 Nuxt 版本中保持稳定性 // 指定 Nuxt 应用程序的兼容性日期,确保应用程序在未来的 Nuxt 版本中保持稳定性
compatibilityDate: '2025-02-28', compatibilityDate: '2025-02-28',
devServer: { devServer: {
https: { https: httpsOptions,
key: fs.readFileSync(path.resolve(__dirname, 'ssl/localhost-key.pem')), host: '0.0.0.0',
cert: fs.readFileSync(path.resolve(__dirname, 'ssl/localhost.pem')) port: 3000,
},
host: '0.0.0.0', // Set the host to 'localhost'
port: 3000, // Set the port to 3000 or any other port you prefer
}, },
}) })