akkoma-fe/src/modules/chat.js

42 lines
996 B
JavaScript
Raw Normal View History

2017-12-05 10:47:10 +00:00
const chat = {
state: {
messages: [],
channel: {state: ''},
socket: null
2017-12-05 10:47:10 +00:00
},
mutations: {
setChannel (state, channel) {
state.channel = channel
},
setSocket (state, socket) {
state.socket = socket
},
2017-12-05 10:47:10 +00:00
addMessage (state, message) {
state.messages.push(message)
state.messages = state.messages.slice(-19, 20)
},
setMessages (state, messages) {
state.messages = messages.slice(-19, 20)
}
},
actions: {
disconnectFromChat (store) {
2019-06-20 03:12:25 +00:00
store.state.socket && store.state.socket.disconnect()
},
2017-12-05 10:47:10 +00:00
initializeChat (store, socket) {
const channel = socket.channel('chat:public')
store.commit('setSocket', socket)
2017-12-05 10:47:10 +00:00
channel.on('new_msg', (msg) => {
store.commit('addMessage', msg)
})
channel.on('messages', ({messages}) => {
store.commit('setMessages', messages)
})
channel.join()
store.commit('setChannel', channel)
}
}
}
export default chat