1 | import { Connector } from './connector';
|
2 | import { SocketIoChannel, SocketIoPrivateChannel, SocketIoPresenceChannel } from './../channel';
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | export class SocketIoConnector extends Connector {
|
8 | |
9 |
|
10 |
|
11 | socket: any;
|
12 |
|
13 | |
14 |
|
15 |
|
16 | channels: { [name: string]: SocketIoChannel } = {};
|
17 |
|
18 | |
19 |
|
20 |
|
21 | connect(): void {
|
22 | let io = this.getSocketIO();
|
23 |
|
24 | this.socket = io(this.options.host, this.options);
|
25 |
|
26 | this.socket.on('reconnect', () => {
|
27 | Object.values(this.channels).forEach((channel) => {
|
28 | channel.subscribe();
|
29 | });
|
30 | });
|
31 |
|
32 | return this.socket;
|
33 | }
|
34 |
|
35 | |
36 |
|
37 |
|
38 | getSocketIO(): any {
|
39 | if (typeof this.options.client !== 'undefined') {
|
40 | return this.options.client;
|
41 | }
|
42 |
|
43 | if (typeof io !== 'undefined') {
|
44 | return io;
|
45 | }
|
46 |
|
47 | throw new Error('Socket.io client not found. Should be globally available or passed via options.client');
|
48 | }
|
49 |
|
50 | |
51 |
|
52 |
|
53 | listen(name: string, event: string, callback: Function): SocketIoChannel {
|
54 | return this.channel(name).listen(event, callback);
|
55 | }
|
56 |
|
57 | |
58 |
|
59 |
|
60 | channel(name: string): SocketIoChannel {
|
61 | if (!this.channels[name]) {
|
62 | this.channels[name] = new SocketIoChannel(this.socket, name, this.options);
|
63 | }
|
64 |
|
65 | return this.channels[name];
|
66 | }
|
67 |
|
68 | |
69 |
|
70 |
|
71 | privateChannel(name: string): SocketIoPrivateChannel {
|
72 | if (!this.channels['private-' + name]) {
|
73 | this.channels['private-' + name] = new SocketIoPrivateChannel(this.socket, 'private-' + name, this.options);
|
74 | }
|
75 |
|
76 | return this.channels['private-' + name] as SocketIoPrivateChannel;
|
77 | }
|
78 |
|
79 | |
80 |
|
81 |
|
82 | presenceChannel(name: string): SocketIoPresenceChannel {
|
83 | if (!this.channels['presence-' + name]) {
|
84 | this.channels['presence-' + name] = new SocketIoPresenceChannel(
|
85 | this.socket,
|
86 | 'presence-' + name,
|
87 | this.options
|
88 | );
|
89 | }
|
90 |
|
91 | return this.channels['presence-' + name] as SocketIoPresenceChannel;
|
92 | }
|
93 |
|
94 | |
95 |
|
96 |
|
97 | leave(name: string): void {
|
98 | let channels = [name, 'private-' + name, 'presence-' + name];
|
99 |
|
100 | channels.forEach((name) => {
|
101 | this.leaveChannel(name);
|
102 | });
|
103 | }
|
104 |
|
105 | |
106 |
|
107 |
|
108 | leaveChannel(name: string): void {
|
109 | if (this.channels[name]) {
|
110 | this.channels[name].unsubscribe();
|
111 |
|
112 | delete this.channels[name];
|
113 | }
|
114 | }
|
115 |
|
116 | |
117 |
|
118 |
|
119 | socketId(): string {
|
120 | return this.socket.id;
|
121 | }
|
122 |
|
123 | |
124 |
|
125 |
|
126 | disconnect(): void {
|
127 | this.socket.disconnect();
|
128 | }
|
129 | }
|