UNPKG

3.27 kBPlain TextView Raw
1import { Connector } from './connector';
2import {
3 PusherChannel,
4 PusherPrivateChannel,
5 PusherEncryptedPrivateChannel,
6 PusherPresenceChannel,
7 PresenceChannel,
8} from './../channel';
9
10/**
11 * This class creates a connector to Pusher.
12 */
13export class PusherConnector extends Connector {
14 /**
15 * The Pusher instance.
16 */
17 pusher: any;
18
19 /**
20 * All of the subscribed channel names.
21 */
22 channels: any = {};
23
24 /**
25 * Create a fresh Pusher connection.
26 */
27 connect(): void {
28 if (typeof this.options.client !== 'undefined') {
29 this.pusher = this.options.client;
30 } else {
31 this.pusher = new Pusher(this.options.key, this.options);
32 }
33 }
34
35 /**
36 * Listen for an event on a channel instance.
37 */
38 listen(name: string, event: string, callback: Function): PusherChannel {
39 return this.channel(name).listen(event, callback);
40 }
41
42 /**
43 * Get a channel instance by name.
44 */
45 channel(name: string): PusherChannel {
46 if (!this.channels[name]) {
47 this.channels[name] = new PusherChannel(this.pusher, name, this.options);
48 }
49
50 return this.channels[name];
51 }
52
53 /**
54 * Get a private channel instance by name.
55 */
56 privateChannel(name: string): PusherChannel {
57 if (!this.channels['private-' + name]) {
58 this.channels['private-' + name] = new PusherPrivateChannel(this.pusher, 'private-' + name, this.options);
59 }
60
61 return this.channels['private-' + name];
62 }
63
64 /**
65 * Get a private encrypted channel instance by name.
66 */
67 encryptedPrivateChannel(name: string): PusherChannel {
68 if (!this.channels['private-encrypted-' + name]) {
69 this.channels['private-encrypted-' + name] = new PusherEncryptedPrivateChannel(
70 this.pusher,
71 'private-encrypted-' + name,
72 this.options
73 );
74 }
75
76 return this.channels['private-encrypted-' + name];
77 }
78
79 /**
80 * Get a presence channel instance by name.
81 */
82 presenceChannel(name: string): PresenceChannel {
83 if (!this.channels['presence-' + name]) {
84 this.channels['presence-' + name] = new PusherPresenceChannel(
85 this.pusher,
86 'presence-' + name,
87 this.options
88 );
89 }
90
91 return this.channels['presence-' + name];
92 }
93
94 /**
95 * Leave the given channel, as well as its private and presence variants.
96 */
97 leave(name: string): void {
98 let channels = [name, 'private-' + name, 'presence-' + name];
99
100 channels.forEach((name: string, index: number) => {
101 this.leaveChannel(name);
102 });
103 }
104
105 /**
106 * Leave the given channel.
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 * Get the socket ID for the connection.
118 */
119 socketId(): string {
120 return this.pusher.connection.socket_id;
121 }
122
123 /**
124 * Disconnect Pusher connection.
125 */
126 disconnect(): void {
127 this.pusher.disconnect();
128 }
129}