import { io } from 'socket.io/client-dist/socket.io' import Vue from 'vue' export default { data() { return { userNotificationOffset: 60 } }, computed: { userIsLoggedIn() { return this.$auth.loggedIn }, userWS: { get() { return this.$store.state.front.userWS }, set(val) { this.$store.commit('front/set', ['userWS', val]) } } }, methods: { initUserWS() { this.userWS = true /// /////////////////////////////////////////// connetct to ws server const socket = io(`${this.$config.WebSocketURL}/user`, { reconnectionDelay: 20000, reconnectionDelayMax: 20000, auth: { token: this.$auth.strategy.token.get() } }) Vue.prototype.$userSocket = socket /// /////////////////////////////////////////// connection error // eslint-disable-next-line node/handle-callback-err socket.on('connect_error', err => { this.$notify({ type: 'error', title: 'خطا', message: 'دریافت اعلانات با مشکل مواجه شد', position: 'top-left', offset: this.userNotificationOffset // duration: 0 }) }) /// /////////////////////////////////////////// events socket.on('connect', () => { // console.log('**************** You have access to notifications') socket.emit('user:fetchAnnouncements') }) socket.on(`user:allNotifs`, data => { this.$store.commit('front/set', ['unreadTickets', data.unreadTickets]) this.$store.commit('front/set', ['draftsCount', data.draftsCount]) }) socket.on(`user:announcements`, data => { this.$store.commit('front/set', ['newUserAnnosCount', data.newUserAnnosCount]) this.$store.commit('front/set', ['userAnnouncements', data.userAnnouncements]) }) socket.on(`user:fetchNewAnnouncements`, data => { socket.emit('user:fetchAnnouncements') }) socket.on(`user:notify`, data => { if (data.type === 'updateUnreadTickets') { // update store this.$store.commit('front/set', ['unreadTickets', data.unreadTickets]) // update DOM if (this.$route.name === 'account-tickets') { this.$nuxt.refresh() } } if (data.type === 'newTicketMsg') { this.$notify({ type: 'success', title: 'توجه', message: 'پیام دارید', position: 'top-left', offset: this.userNotificationOffset }) if (this.$route.name === 'account-tickets-ticket') { this.$nuxt.refresh() setTimeout(() => { window.scrollTo(0, document.body.scrollHeight) }, 500) } } if (data.type === 'updateDraftsCount') { // update store this.$store.commit('front/set', ['draftsCount', data.draftsCount]) // update DOM if (this.$route.name === 'account-drafts') { this.$nuxt.refresh() } } }) socket.on(`user:notifyAll`, data => { if (data.type === 'fetchNewAnnouncements') { socket.emit('user:fetchAnnouncements') this.$notify({ type: 'success', title: 'توجه', message: 'پیام جدید در اعلانات دارید', position: 'top-left', offset: this.userNotificationOffset }) } }) } }, mounted() { if (this.userIsLoggedIn && this.$auth.hasScope('user') && !this.userWS) { this.initUserWS() } } }