]>
Commit | Line | Data |
---|---|---|
67ed6552 | 1 | import { Subject } from 'rxjs' |
84c7cde6 | 2 | import { Injectable, NgZone } from '@angular/core' |
67ed6552 | 3 | import { UserNotification as UserNotificationServer } from '@shared/models' |
9a39392a | 4 | import { environment } from '../../../environments/environment' |
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 ( | |
84c7cde6 C |
16 | private auth: AuthService, |
17 | private ngZone: NgZone | |
9a39392a C |
18 | ) {} |
19 | ||
20 | dispatch (type: NotificationEvent, notification?: UserNotificationServer) { | |
21 | this.notificationSubject.next({ type, notification }) | |
22 | } | |
23 | ||
41d71344 C |
24 | async getMyNotificationsSocket () { |
25 | await this.initSocket() | |
9a39392a C |
26 | |
27 | return this.notificationSubject.asObservable() | |
28 | } | |
29 | ||
41d71344 C |
30 | private async initSocket () { |
31 | if (this.socket) return | |
32 | ||
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 | |
9a39392a | 35 | |
84c7cde6 C |
36 | this.ngZone.runOutsideAngular(() => { |
37 | this.socket = io(environment.apiUrl + '/user-notifications', { | |
38 | query: { accessToken: this.auth.getAccessToken() } | |
39 | }) | |
9a39392a | 40 | |
84c7cde6 C |
41 | this.socket.on('new-notification', (n: UserNotificationServer) => this.dispatch('new', n)) |
42 | }) | |
9a39392a C |
43 | } |
44 | } |