🎨 organize websocket code structure

This commit is contained in:
landaiqing
2024-09-27 00:42:50 +08:00
parent 4f42d1c5b4
commit 172bf00d93
7 changed files with 80 additions and 38 deletions

View File

@@ -3,6 +3,7 @@ import {useThemeStore} from "@/store/modules/themeStore.ts";
import {langStore} from "@/store/modules/langStore.ts";
import {useClientStore} from "@/store/modules/clientStore.ts";
import {useCommentStore} from "@/store/modules/commentStore.ts";
import {useWebSocketStore} from "@/store/modules/websocketStore.ts";
export default function useStore() {
return {
@@ -11,5 +12,6 @@ export default function useStore() {
lang: langStore(),
client: useClientStore(),
comment: useCommentStore(),
websocket: useWebSocketStore(),
};
}

View File

@@ -0,0 +1,45 @@
// useWebSocketStore.ts
import {defineStore} from 'pinia';
import {onUnmounted, reactive} from 'vue';
import {WebSocketService} from '@/utils/websocket/websocket.ts';
type MessageCallback = (data: any) => void;
type EventCallback = () => void;
export const useWebSocketStore = defineStore('websocket', () => {
const state = reactive({
wsService: null as WebSocketService | null,
});
function initialize(options: { url: string; protocols?: string | string[]; reconnectTimeout?: number }) {
state.wsService = new WebSocketService(options);
state.wsService.open();
onUnmounted(() => {
state.wsService?.close(true);
});
}
function sendMessage(data: any) {
state.wsService?.send(data);
}
function on(event: 'message', callback: MessageCallback) {
state.wsService?.on(event, callback);
}
function onEvent(event: 'open' | 'error' | 'close', callback: EventCallback) {
state.wsService?.on(event, callback);
}
function close() {
state.wsService?.close();
}
return {
initialize,
sendMessage,
on,
onEvent,
close,
};
});