Skip to content

Instantly share code, notes, and snippets.

@cannap
Last active July 5, 2019 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cannap/6edfe3f7889ae1da018b662ffd7baa5f to your computer and use it in GitHub Desktop.
Save cannap/6edfe3f7889ae1da018b662ffd7baa5f to your computer and use it in GitHub Desktop.
import Echo from 'laravel-echo'
import Vue from 'vue'
window.io = require('socket.io-client')
const host = process.env.WEBSOCKET
/**
* In Components you can now write
* socket: {
channels: [
{
'nice-public': {
type: 'public',
events: {
'.message.sent' (payload, instance) {
console.log(instance.$sockets)
}
}
}
}
]
},
*/
const Socket = {
install (Vue, options = {}) {
Vue.prototype.$sockets = new Map()
Vue.mixin({
mounted () {
const conf = this.$options['socket']
if (conf) {
const channels = conf.channels
// Go trought channels
channels.forEach(channel => {
let channelInstance
const channelName = Object.getOwnPropertyNames(channel)[0]
const events = Object.keys(channel[channelName].events)
const type = channel[channelName].type || 'public'
if (type === 'public') {
channelInstance = this.$echo.channel(channelName)
}
if (type === 'private') {
channelInstance = this.$echo.private(channelName)
}
// Todo: logout from pricvate channel when user logsout and on login join them again
this.$sockets.set(channelName, { type, socket: channelInstance })
if (events) {
events.forEach(event => {
channelInstance.listen(event, payload => {
channel[channelName].events[event](payload, this)
})
}, this)
}
})
}
},
beforeDestroy () {
if (!this.$sockets.size > 0) return
for (let [key] of this.$sockets) {
this.$sockets.delete(key)
this.$echo.leave(key)
}
}
})
}
}
export default ({ store, app: { $auth } }, inject) => {
console.log(store.state.auth.loggedIn)
const echoOptions = {
broadcaster: 'socket.io',
host
}
const echo = new Echo(echoOptions)
Vue.use(Socket)
inject('echo', echo)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment