koel/resources/assets/js/services/socket.js

59 lines
1.4 KiB
JavaScript
Raw Normal View History

2017-08-25 00:37:21 +00:00
import Pusher from 'pusher-js'
import { userStore } from '../stores'
import { ls } from '.'
export const socket = {
pusher: null,
channel: null,
2017-08-26 21:42:14 +00:00
async init () {
return new Promise((resolve, reject) => {
if (!process.env.PUSHER_APP_KEY) {
return resolve()
}
this.pusher = new Pusher(process.env.PUSHER_APP_KEY, {
authEndpoint: '/api/broadcasting/auth',
auth: {
headers: {
2017-08-28 11:13:00 +00:00
Authorization: `Bearer ${ls.get('jwt-token')}`
2017-08-26 21:42:14 +00:00
}
},
cluster: process.env.PUSHER_APP_CLUSTER,
encrypted: true
})
2017-08-28 11:13:00 +00:00
2017-08-26 21:42:14 +00:00
this.channel = this.pusher.subscribe('private-koel')
this.channel.bind('pusher:subscription_succeeded', () => {
return resolve()
})
this.channel.bind('pusher:subscription_error', () => {
return resolve()
})
2017-08-25 00:37:21 +00:00
})
},
/**
* Broadcast an event with Pusher.
* @param {string} eventName The event's name
* @param {Object} data The event's data
*/
2017-08-28 11:13:00 +00:00
broadcast (eventName, data = {}) {
2017-08-25 00:37:21 +00:00
this.channel && this.channel.trigger(`client-${eventName}.${userStore.current.id}`, data)
return this
},
/**
* Listen to an event.
* @param {string} eventName The event's name
2017-08-28 11:13:00 +00:00
* @param {Function} cb
2017-08-25 00:37:21 +00:00
*/
2017-08-28 11:13:00 +00:00
listen (eventName, cb) {
2017-08-25 00:37:21 +00:00
this.channel && this.channel.bind(`client-${eventName}.${userStore.current.id}`, data => cb(data))
2017-08-28 11:13:00 +00:00
2017-08-25 00:37:21 +00:00
return this
}
}