aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/core/notification/user-notification-socket.service.ts
blob: f367d9ae465d823c4fd6290fad8960ba08091a0f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { Injectable } from '@angular/core'
import { environment } from '../../../environments/environment'
import { UserNotification as UserNotificationServer } from '../../../../../shared'
import { Subject } from 'rxjs'
import * as io from 'socket.io-client'
import { AuthService } from '../auth'

export type NotificationEvent = 'new' | 'read' | 'read-all'

@Injectable()
export class UserNotificationSocket {
  private notificationSubject = new Subject<{ type: NotificationEvent, notification?: UserNotificationServer }>()

  private socket: SocketIOClient.Socket

  constructor (
    private auth: AuthService
  ) {}

  dispatch (type: NotificationEvent, notification?: UserNotificationServer) {
    this.notificationSubject.next({ type, notification })
  }

  getMyNotificationsSocket () {
    const socket = this.getSocket()

    socket.on('new-notification', (n: UserNotificationServer) => this.dispatch('new', n))

    return this.notificationSubject.asObservable()
  }

  private getSocket () {
    if (this.socket) return this.socket

    this.socket = io(environment.apiUrl + '/user-notifications', {
      query: { accessToken: this.auth.getAccessToken() }
    })

    return this.socket
  }
}