]>
Commit | Line | Data |
---|---|---|
9a39392a C |
1 | import { Injectable } from '@angular/core' |
2 | import { environment } from '../../../environments/environment' | |
3 | import { UserNotification as UserNotificationServer } from '../../../../../shared' | |
4 | import { Subject } from 'rxjs' | |
9a39392a C |
5 | import { AuthService } from '../auth' |
6 | ||
7 | export type NotificationEvent = 'new' | 'read' | 'read-all' | |
8 | ||
9 | @Injectable() | |
10 | export class UserNotificationSocket { | |
11 | private notificationSubject = new Subject<{ type: NotificationEvent, notification?: UserNotificationServer }>() | |
12 | ||
13 | private socket: SocketIOClient.Socket | |
14 | ||
15 | constructor ( | |
16 | private auth: AuthService | |
17 | ) {} | |
18 | ||
19 | dispatch (type: NotificationEvent, notification?: UserNotificationServer) { | |
20 | this.notificationSubject.next({ type, notification }) | |
21 | } | |
22 | ||
41d71344 C |
23 | async getMyNotificationsSocket () { |
24 | await this.initSocket() | |
9a39392a C |
25 | |
26 | return this.notificationSubject.asObservable() | |
27 | } | |
28 | ||
41d71344 C |
29 | private async initSocket () { |
30 | if (this.socket) return | |
31 | ||
32 | // FIXME: import('..') returns a struct module, containing a "default" field corresponding to our sanitizeHtml function | |
33 | const io: typeof import ('socket.io-client') = (await import('socket.io-client') as any).default | |
9a39392a C |
34 | |
35 | this.socket = io(environment.apiUrl + '/user-notifications', { | |
36 | query: { accessToken: this.auth.getAccessToken() } | |
37 | }) | |
38 | ||
41d71344 | 39 | this.socket.on('new-notification', (n: UserNotificationServer) => this.dispatch('new', n)) |
9a39392a C |
40 | } |
41 | } |