1 import { Injectable } from '@angular/core'
2 import { environment } from '../../../environments/environment'
3 import { UserNotification as UserNotificationServer } from '../../../../../shared'
4 import { Subject } from 'rxjs'
5 import * as io from 'socket.io-client'
6 import { AuthService } from '../auth'
8 export type NotificationEvent = 'new' | 'read' | 'read-all'
11 export class UserNotificationSocket {
12 private notificationSubject = new Subject<{ type: NotificationEvent, notification?: UserNotificationServer }>()
14 private socket: SocketIOClient.Socket
17 private auth: AuthService
20 dispatch (type: NotificationEvent, notification?: UserNotificationServer) {
21 this.notificationSubject.next({ type, notification })
24 getMyNotificationsSocket () {
25 const socket = this.getSocket()
27 socket.on('new-notification', (n: UserNotificationServer) => this.dispatch('new', n))
29 return this.notificationSubject.asObservable()
32 private getSocket () {
33 if (this.socket) return this.socket
35 this.socket = io(environment.apiUrl + '/user-notifications', {
36 query: { accessToken: this.auth.getAccessToken() }