This commit is contained in:
2026-02-26 22:34:44 +03:00
parent 2cc21bb284
commit 54fa90b2a5
22 changed files with 1108 additions and 451 deletions

View File

@@ -1,141 +0,0 @@
import { ref, onUnmounted, onMounted } from 'vue'
export interface Message {
id: number
text: string
userId: string
createdAt: string
}
export interface Chat {
id: string
type_id: number
users: User[]
}
export interface User {
id: number
email: string
}
export interface WsData {
type: WsDataType2
// data: Chat | Message | User | User[] | Message[] | Chat[]
data: unknown
}
export enum WsDataType2 {
GET_CHATS = 'GET_CHATS',
GET_USERS = 'GET_USERS',
GET_MESSAGES = 'GET_MESSAGES',
CREATE_MESSAGE = 'CREATE_MESSAGE',
CHATS = 'CHATS',
USER = 'USER',
MESSAGES = 'MESSAGES',
STATUS = 'STATUS',
ERROR = 'ERROR',
}
export enum COMMAND2 {
CONNECT = 'CONNECT',
SEND = 'SEND',
CLOSE = 'CLOSE',
}
export function useSharedWebSocket(options?: { url?: string; autoConnect?: true }) {
const url = options?.url || 'ws://localhost:3000/ws'
const autoConnect = options?.autoConnect ?? false
const messages = ref<Message[]>([])
const chats = ref<Chat[]>([])
const users = ref<unknown[]>([])
const isConnected = ref(false)
const error = ref<string>()
const worker = ref<SharedWorker>()
const init = () => {
console.log('INIT WORKER')
if (!window.SharedWorker) {
console.log('SharedWorker not supported')
error.value = 'SharedWorker not supported'
}
worker.value = new SharedWorker(new URL('@/workers/worker.js', import.meta.url), {
type: 'module',
})
worker.value.port.onmessage = (event) => {
const { type, data, connected, message } = event.data
switch (type) {
case WsDataType2.USER:
break
case WsDataType2.CHATS:
chats.value = data
break
case WsDataType2.MESSAGES:
messages.value = data
// if (options.onMessage) {
// options.onMessage(data)
// }
break
case WsDataType2.CREATE_MESSAGE:
messages.value.push(data)
break
case WsDataType2.STATUS:
isConnected.value = connected
break
case WsDataType2.ERROR:
error.value = message
logout()
break
}
}
worker.value.port.postMessage({
command: COMMAND2.CONNECT,
data: { url: url, token: getToken() },
})
}
function logout() {
return localStorage.removeItem('token')
}
function getToken() {
return localStorage.getItem('token')
}
const send = (data: WsData) => {
if (worker.value) {
worker.value.port.postMessage({
command: COMMAND2.SEND,
data: data,
})
}
}
const close = () => {
if (worker.value) {
worker.value.port.postMessage({ command: COMMAND2.CLOSE })
}
}
onMounted(() => {
if (autoConnect) init()
})
onUnmounted(() => {
if (worker.value) close()
})
return {
messages,
chats,
isConnected,
error,
send,
close,
init,
}
}