2017-12-05 10:47:10 +00:00
|
|
|
const chat = {
|
|
|
|
state: {
|
|
|
|
messages: [],
|
2019-07-05 07:02:14 +00:00
|
|
|
channel: { state: '' },
|
2019-03-10 18:23:27 +00:00
|
|
|
socket: null
|
2017-12-05 10:47:10 +00:00
|
|
|
},
|
|
|
|
mutations: {
|
|
|
|
setChannel (state, channel) {
|
|
|
|
state.channel = channel
|
|
|
|
},
|
2019-03-10 18:23:27 +00:00
|
|
|
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: {
|
2019-03-10 18:23:27 +00:00
|
|
|
disconnectFromChat (store) {
|
2019-06-20 03:12:25 +00:00
|
|
|
store.state.socket && store.state.socket.disconnect()
|
2019-03-10 18:23:27 +00:00
|
|
|
},
|
2017-12-05 10:47:10 +00:00
|
|
|
initializeChat (store, socket) {
|
|
|
|
const channel = socket.channel('chat:public')
|
2019-03-10 18:23:27 +00:00
|
|
|
store.commit('setSocket', socket)
|
2017-12-05 10:47:10 +00:00
|
|
|
channel.on('new_msg', (msg) => {
|
|
|
|
store.commit('addMessage', msg)
|
|
|
|
})
|
2019-07-05 07:02:14 +00:00
|
|
|
channel.on('messages', ({ messages }) => {
|
2017-12-05 10:47:10 +00:00
|
|
|
store.commit('setMessages', messages)
|
|
|
|
})
|
|
|
|
channel.join()
|
|
|
|
store.commit('setChannel', channel)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default chat
|