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 async getMyNotificationsSocket () {
25 await this.initSocket()
27 return this.notificationSubject.asObservable()
30 private async initSocket () {
31 if (this.socket) return
33 // FIXME: import('..') returns a struct module, containing a "default" field corresponding to our sanitizeHtml function
34 const io: typeof import ('socket.io-client') = (await import('socket.io-client') as any).default
36 this.socket = io(environment.apiUrl + '/user-notifications', {
37 query: { accessToken: this.auth.getAccessToken() }
40 this.socket.on('new-notification', (n: UserNotificationServer) => this.dispatch('new', n))