This commit is contained in:
2026-02-23 23:56:39 +03:00
parent 25750fee51
commit 2cc21bb284
15 changed files with 340 additions and 94 deletions

View File

@@ -1,5 +1,122 @@
import { defineStore } from 'pinia'
import { onMounted, onUnmounted, ref } from 'vue'
import { type Chat, useChatsStore } from '@/stores/chats.ts'
import { useAuthStore } from '@/stores/auth.ts'
import { type Message, useMessagesStore } from '@/stores/messages.ts'
export const useSockets = defineStore('sockets', () => {
return {}
export enum SocketDataReq {
GET_CHATS = 'GET_CHATS',
CREATE_CHAT = 'CREATE_CHAT',
GET_USERS = 'GET_USERS',
GET_USER = 'GET_USER',
GET_MESSAGES = 'GET_MESSAGES',
CREATE_MESSAGE = 'CREATE_MESSAGE',
}
export enum SocketDataRes {
USERS = 'USERS',
CHATS = 'CHATS',
MESSAGES = 'MESSAGES',
MESSAGE = 'MESSAGE',
USER = 'USER',
STATUS = 'STATUS',
ERROR = 'ERROR',
}
export enum COMMAND {
CONNECT = 'CONNECT',
SEND = 'SEND',
CLOSE = 'CLOSE',
}
export const useSocketsStore = defineStore('sockets', () => {
const url = 'ws://localhost:3000/ws'
const authStore = useAuthStore()
const chatsStore = useChatsStore()
const messagesStore = useMessagesStore()
const isConnected = ref(false)
const error = ref<string>()
const worker = ref<SharedWorker>()
function init() {
console.log('INIT SHARED 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 SocketDataRes.USERS:
console.log('USERS_LIST', data)
break
case SocketDataRes.USER:
console.log('USER', data)
authStore.me = data
break
case SocketDataRes.CHATS:
console.log('CHATS', data)
chatsStore.chats = data
break
case SocketDataRes.MESSAGES:
console.log('MESSAGES', data)
messagesStore.messages = data.reverse()
// if (options.onMessage) {
// options.onMessage(data)
// }
break
case SocketDataRes.MESSAGE:
console.log('MESSAGE', data)
messagesStore.messages.push(data)
break
case SocketDataRes.STATUS:
isConnected.value = connected
break
case SocketDataRes.ERROR:
error.value = message
authStore.logout()
break
}
}
connect()
}
function postMessage(command: COMMAND, data?: unknown) {
if (worker.value) worker.value.port.postMessage({ command, data })
}
function connect() {
postMessage(COMMAND.CONNECT, { url: url, token: authStore.getToken() })
}
const send = (data: unknown) => {
postMessage(COMMAND.SEND, data)
}
const close = () => {
postMessage(COMMAND.CLOSE)
}
onUnmounted(() => {
if (worker.value) close()
})
return {
isConnected,
error,
send,
close,
init,
}
})