acdr-ui/dist/build/mp-weixin/modules/mall/sheep/hooks/useWebSocket.js
2024-10-01 09:15:35 +08:00

2 lines
1.4 KiB
JavaScript

"use strict";const e=require("../../../../common/vendor.js"),t=require("../config/index.js"),n=require("../util/index.js");exports.useWebSocket=function(o){const r=e.reactive({url:(t.baseUrl+t.websocketPath).replace("http","ws")+"?token="+e.index.getStorageSync("token"),isReconnecting:!1,reconnectInterval:3e3,heartBeatInterval:5e3,pingTimeoutDuration:1e3,heartBeatTimer:null,destroy:!1,pingTimeout:null,reconnectTimeout:null,onConnected:()=>{},onClosed:()=>{},onMessage:e=>{}}),a=e.ref(null),i=()=>{r.heartBeatTimer=setInterval((()=>{var e;e="ping",a.value&&!r.destroy&&a.value.send({data:e}),r.pingTimeout=setTimeout((()=>{c()}),r.pingTimeoutDuration)}),r.heartBeatInterval)},u=()=>{clearInterval(r.heartBeatTimer),l()},c=()=>{!r.destroy&&a.value&&(r.isReconnecting=!0,r.reconnectTimeout&&clearTimeout(r.reconnectTimeout),r.reconnectTimeout=setTimeout((()=>{r.destroy||(r.isReconnecting=!1,s())}),r.reconnectInterval))},l=()=>{r.pingTimeout&&(clearTimeout(r.pingTimeout),r.pingTimeout=null)},s=()=>{r.destroy=!1,n.copyValueToTarget(r,o),a.value=e.index.connectSocket({url:r.url,complete:()=>{},success:()=>{}}),a.value.onOpen((()=>{r.onConnected(),i()})),a.value.onMessage((e=>{try{"pong"===e.data?l():r.onMessage(JSON.parse(e.data))}catch(t){}})),a.value.onClose((e=>{r.destroy?r.onClosed():(u(),c())}))};return s(),e.onBeforeUnmount((()=>{r.destroy=!0,u(),r.reconnectTimeout&&clearTimeout(r.reconnectTimeout),a.value&&(a.value.close(),a.value=null)})),{options:r}};