Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 105d1bd

Browse files
Add files via upload
1 parent 2bedaea commit 105d1bd

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { EventBus } from '@/event-bus';
2+
import { SIGNALR_CONFIG } from '../config';
3+
import { HubConnection, HubConnectionBuilder, HubConnectionState } from '@microsoft/signalr';
4+
5+
/**
6+
* SignalR API abstraction layer communication.
7+
* Configures/manages hub connections (typescript singleton pattern).
8+
*/
9+
class SignalRService {
10+
private _hubConnection: HubConnection;
11+
private static _signalRService: SignalRService;
12+
13+
private constructor() {
14+
this.createConnection();
15+
this.registerOnServerEvents();
16+
}
17+
18+
public static get Instance(): SignalRService {
19+
return this._signalRService || (this._signalRService = new this());
20+
}
21+
22+
public startConnection(): void {
23+
if (this._hubConnection.state === HubConnectionState.Disconnected) {
24+
this._hubConnection
25+
.start()
26+
.catch((e) => console.error(e));
27+
}
28+
}
29+
30+
private createConnection(): void {
31+
this._hubConnection = new HubConnectionBuilder()
32+
.withUrl(SIGNALR_CONFIG.baseUrl)
33+
.build();
34+
}
35+
36+
private hubToastMessage(
37+
message: string,
38+
title: string = SIGNALR_CONFIG.messageTitle,
39+
delay: number = SIGNALR_CONFIG.messageDelay
40+
): void {
41+
setTimeout(() => {
42+
EventBus.$snotify.info(message, title);
43+
}, delay);
44+
}
45+
46+
private registerOnServerEvents(): void {
47+
this._hubConnection.on(SIGNALR_CONFIG.events.login, () => {
48+
this.hubToastMessage('A user has logged in');
49+
});
50+
51+
this._hubConnection.on(SIGNALR_CONFIG.events.logout, () => {
52+
this.hubToastMessage('A user has logged out');
53+
});
54+
55+
this._hubConnection.on(SIGNALR_CONFIG.events.closeConnections, (reason: string) => {
56+
this._hubConnection
57+
.stop()
58+
.then(() => {
59+
this.hubToastMessage(`Hub closed (${reason})`);
60+
});
61+
});
62+
}
63+
}
64+
65+
export const SignalRApi = SignalRService.Instance;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /