Created
September 22, 2019 23:48
-
-
Save unr/1910b603ec5d9e228bed04a57c7cd88e to your computer and use it in GitHub Desktop.
WIP Version of a custom Pusher Plugin for Nuxt.js - This is being used with a Laravel/ backend, where we have now replaced echo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// plugins/pusher.client.js | |
// Browser only, create a new instance of pusher on load | |
// Accessible via this.$pusher | |
import Pusher from 'pusher-js'; | |
export default ({ env, store }, inject) => { | |
// we need withCredentials for our CORS setup | |
Pusher.Runtime.createXHR = () => { | |
var xhr = new XMLHttpRequest(); | |
xhr.withCredentials = true; | |
return xhr; | |
}; | |
const pusher = new Pusher(env.pusherAppKey, { | |
cluster: env.pusherCluster, | |
encrypted: true, | |
// Laravel Echo basically just set up this endpoint | |
authEndpoint: `${env.apiUrl}broadcasting/auth` | |
}); | |
// Pass a channel ID to leave it | |
const leaveChannel = channelName => { | |
const channel = pusher.channel(channelName); | |
if (channel) channel.unsubscribe(); | |
}; | |
// You can connect to default channels here | |
pusher.subscribe('default').bind('someEvent', notification => { | |
store.commit('handleSomeEvent', notification); | |
}); | |
// Now accessible in views/vuex | |
// So you can call this.$pusher from anywhere | |
// You can also dynamically call $leaveChannel if needed | |
inject('pusher', pusher); | |
inject('leaveChannel', leaveChannel); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment