import { io } from 'socket.io/client-dist/socket.io' import Vue from 'vue' export default { data() { return { agentNotificationOffset: 60 } }, computed: { user() { return this.$auth.user }, userIsLoggedIn() { return this.$auth.loggedIn }, agentWS: { get() { return this.$store.state.front.agentWS }, set(val) { this.$store.commit('front/set', ['agentWS', val]) } } }, methods: { initAgentWS() { this.agentWS = true /// /////////////////////////////////////////// connetct to ws server const socket = io(`${this.$config.WebSocketURL}/agent`, { reconnectionDelay: 20000, reconnectionDelayMax: 20000, auth: { token: this.$auth.strategy.token.get() } }) Vue.prototype.$agentSocket = socket /// /////////////////////////////////////////// connection error // eslint-disable-next-line node/handle-callback-err socket.on('connect_error', err => {}) /// /////////////////////////////////////////// events socket.on('connect', () => { // console.log('**************** You have access to agent notifications') socket.emit('agent:fetchAnnouncements') }) socket.on(`agent:allNotifs`, data => { this.$store.commit('front/set', ['agentInbox', data.agentInbox]) }) socket.on(`agent:announcements`, data => { this.$store.commit('front/set', ['newAgentAnnosCount', data.newAgentAnnosCount]) this.$store.commit('front/set', ['agentAnnouncements', data.agentAnnouncements]) }) socket.on(`agent:fetchNewAnnouncements`, data => { socket.emit('agent:fetchAnnouncements') }) socket.on(`agent:notify`, data => { if (data.type === 'updateAgentInbox') { // update store this.$store.commit('front/set', ['agentInbox', data.agentInbox]) // update DOM if (this.$route.name === 'account-agents-inbox') { this.$nuxt.refresh() } } if (data.type === 'newAgentInbox') { // sent ui notif this.$notify({ type: 'success', title: 'توجه', message: ' فرم گارانتی جدید در صندوق ورودی شما قرار گرفت', position: 'top-left', offset: this.agentNotificationOffset, duration: 10 * 1000 }) } }) socket.on(`agent:notifyAll`, data => { if (data.type === 'fetchNewAnnouncements') { socket.emit('agent:fetchAnnouncements') this.$notify({ type: 'success', title: 'توجه', message: 'پیام جدید در اطلاعیه های نمایندگان دارید', position: 'top-left', offset: this.userNotificationOffset }) } }) } }, mounted() { if (this.userIsLoggedIn && this.user.isAgent && !this.agentWS) { this.initAgentWS() } } }