UNPKG

2.47 kBPlain TextView Raw
1import { Channel, PresenceChannel } from './../channel';
2
3export abstract class Connector {
4 /**
5 * Default connector options.
6 */
7 private _defaultOptions: any = {
8 auth: {
9 headers: {},
10 },
11 authEndpoint: '/broadcasting/auth',
12 broadcaster: 'pusher',
13 csrfToken: null,
14 host: null,
15 key: null,
16 namespace: 'App.Events',
17 };
18
19 /**
20 * Connector options.
21 */
22 options: any;
23
24 /**
25 * Create a new class instance.
26 */
27 constructor(options: any) {
28 this.setOptions(options);
29 this.connect();
30 }
31
32 /**
33 * Merge the custom options with the defaults.
34 */
35 protected setOptions(options: any): any {
36 this.options = Object.assign(this._defaultOptions, options);
37
38 if (this.csrfToken()) {
39 this.options.auth.headers['X-CSRF-TOKEN'] = this.csrfToken();
40 }
41
42 return options;
43 }
44
45 /**
46 * Extract the CSRF token from the page.
47 */
48 protected csrfToken(): null | string {
49 let selector;
50
51 if (typeof window !== 'undefined' && window['Laravel'] && window['Laravel'].csrfToken) {
52 return window['Laravel'].csrfToken;
53 } else if (this.options.csrfToken) {
54 return this.options.csrfToken;
55 } else if (
56 typeof document !== 'undefined' &&
57 typeof document.querySelector === 'function' &&
58 (selector = document.querySelector('meta[name="csrf-token"]'))
59 ) {
60 return selector.getAttribute('content');
61 }
62
63 return null;
64 }
65
66 /**
67 * Create a fresh connection.
68 */
69 abstract connect(): void;
70
71 /**
72 * Get a channel instance by name.
73 */
74 abstract channel(channel: string): Channel;
75
76 /**
77 * Get a private channel instance by name.
78 */
79 abstract privateChannel(channel: string): Channel;
80
81 /**
82 * Get a presence channel instance by name.
83 */
84 abstract presenceChannel(channel: string): PresenceChannel;
85
86 /**
87 * Leave the given channel, as well as its private and presence variants.
88 */
89 abstract leave(channel: string): void;
90
91 /**
92 * Leave the given channel.
93 */
94 abstract leaveChannel(channel: string): void;
95
96 /**
97 * Get the socket_id of the connection.
98 */
99 abstract socketId(): string;
100
101 /**
102 * Disconnect from the Echo server.
103 */
104 abstract disconnect(): void;
105}