2022-04-15 14:24:30 +00:00
|
|
|
import Pusher from 'pusher-js'
|
|
|
|
|
|
|
|
import { userStore } from '@/stores'
|
2022-05-14 18:49:45 +00:00
|
|
|
import { authService } from '@/services'
|
2022-04-15 14:24:30 +00:00
|
|
|
|
2022-04-24 08:50:45 +00:00
|
|
|
export const socketService = {
|
2022-04-15 14:24:30 +00:00
|
|
|
pusher: null as Pusher.Pusher | null,
|
|
|
|
channel: null as Pusher.Channel | null,
|
|
|
|
|
|
|
|
async init (): Promise<void> {
|
|
|
|
return new Promise(resolve => {
|
|
|
|
if (!window.PUSHER_APP_KEY) {
|
|
|
|
return resolve()
|
|
|
|
}
|
|
|
|
|
|
|
|
this.pusher = new Pusher(window.PUSHER_APP_KEY, {
|
|
|
|
authEndpoint: `${window.BASE_URL}api/broadcasting/auth`,
|
|
|
|
auth: {
|
|
|
|
headers: {
|
2022-04-24 08:50:45 +00:00
|
|
|
Authorization: `Bearer ${authService.getToken()}`
|
2022-04-15 14:24:30 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
cluster: window.PUSHER_APP_CLUSTER,
|
|
|
|
encrypted: true
|
|
|
|
})
|
|
|
|
|
|
|
|
this.channel = this.pusher.subscribe('private-koel')
|
|
|
|
this.channel.bind('pusher:subscription_succeeded', () => resolve())
|
|
|
|
this.channel.bind('pusher:subscription_error', () => resolve())
|
|
|
|
})
|
|
|
|
},
|
|
|
|
|
|
|
|
broadcast (eventName: string, data: any = {}) {
|
|
|
|
this.channel && this.channel.trigger(`client-${eventName}.${userStore.current.id}`, data)
|
|
|
|
return this
|
|
|
|
},
|
|
|
|
|
2022-05-05 15:30:10 +00:00
|
|
|
listen (eventName: string, cb: Closure) {
|
2022-04-15 14:24:30 +00:00
|
|
|
this.channel && this.channel.bind(`client-${eventName}.${userStore.current.id}`, data => cb(data))
|
|
|
|
return this
|
|
|
|
}
|
|
|
|
}
|