2017-12-05 02:47:10 -08:00
|
|
|
const chat = {
|
|
|
|
state: {
|
|
|
|
messages: [],
|
2019-03-10 11:23:27 -07:00
|
|
|
channel: {state: ''},
|
|
|
|
socket: null
|
2017-12-05 02:47:10 -08:00
|
|
|
},
|
|
|
|
mutations: {
|
|
|
|
setChannel (state, channel) {
|
|
|
|
state.channel = channel
|
|
|
|
},
|
2019-03-10 11:23:27 -07:00
|
|
|
setSocket (state, socket) {
|
|
|
|
state.socket = socket
|
|
|
|
},
|
2017-12-05 02:47:10 -08: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 11:23:27 -07:00
|
|
|
disconnectFromChat (store) {
|
2019-06-19 20:12:25 -07:00
|
|
|
store.state.socket && store.state.socket.disconnect()
|
2019-03-10 11:23:27 -07:00
|
|
|
},
|
2017-12-05 02:47:10 -08:00
|
|
|
initializeChat (store, socket) {
|
|
|
|
const channel = socket.channel('chat:public')
|
2019-03-10 11:23:27 -07:00
|
|
|
store.commit('setSocket', socket)
|
2017-12-05 02:47:10 -08: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
|