hgh_admin/resources/js/views/apps/chat/useChatStore.js
2024-05-29 22:34:28 +05:00

81 lines
2.0 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

export const useChatStore = defineStore('chat', {
// arrow function recommended for full type inference
state: () => ({
contacts: [],
chatsContacts: [],
profileUser: undefined,
activeChat: null,
}),
actions: {
async fetchChatsAndContacts(q) {
const { data, error } = await useApi(createUrl('/apps/chat/chats-and-contacts', {
query: {
q,
},
}))
if (error.value) {
console.log(error.value)
}
else {
const { chatsContacts, contacts, profileUser } = data.value
this.chatsContacts = chatsContacts
this.contacts = contacts
this.profileUser = profileUser
}
},
async getChat(userId) {
const res = await $api(`/apps/chat/chats/${userId}`)
this.activeChat = res
},
async sendMsg(message) {
const senderId = this.profileUser?.id
const response = await $api(`apps/chat/chats/${this.activeChat?.contact.id}`, {
method: 'POST',
body: { message, senderId },
})
const { msg, chat } = response
// ? If it's not undefined => New chat is created (Contact is not in list of chats)
if (chat !== undefined) {
const activeChat = this.activeChat
this.chatsContacts.push({
...activeChat.contact,
chat: {
id: chat.id,
lastMessage: [],
unseenMsgs: 0,
messages: [msg],
},
})
if (this.activeChat) {
this.activeChat.chat = {
id: chat.id,
messages: [msg],
unseenMsgs: 0,
userId: this.activeChat?.contact.id,
}
}
}
else {
this.activeChat?.chat?.messages.push(msg)
}
// Set Last Message for active contact
const contact = this.chatsContacts.find(c => {
if (this.activeChat)
return c.id === this.activeChat.contact.id
return false
})
contact.chat.lastMessage = msg
},
},
})