-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
90 lines (73 loc) · 2.61 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { Participant } from '../../common/types/participant.types';
import { StoreType } from '../../common/types/stores.types';
import { Logger } from '../../common/utils';
import { BaseComponent } from '../base';
import { ComponentNames } from '../types';
import { Channel } from './channel';
import { RealtimeComponentEvent, RealtimeComponentState } from './types';
export class Realtime extends BaseComponent {
protected logger: Logger;
public name: ComponentNames;
private declare localParticipant: Participant;
private state: RealtimeComponentState = RealtimeComponentState.STOPPED;
private channels: Array<Channel> = [];
constructor() {
super();
this.name = ComponentNames.REALTIME;
this.logger = new Logger('@superviz/sdk/realtime-component');
const { localParticipant } = this.useStore(StoreType.GLOBAL);
localParticipant.subscribe();
}
public connect(name: string): Channel {
if (this.state !== RealtimeComponentState.STARTED) {
const message =
"[SuperViz] Realtime component is not started yet. You can't connect to a channel before start";
this.logger.log(message);
console.warn(message);
return;
}
const channel = new Channel(name, this.ioc, this.localParticipant);
this.channels.push(channel);
return channel;
}
protected start(): void {
this.logger.log('started');
this.changeState(RealtimeComponentState.STARTED);
}
protected destroy(): void {
this.logger.log('destroyed');
this.changeState(RealtimeComponentState.STOPPED);
this.disconnectToAllChannels();
}
/**
* @function disconnectToAllChannels
* @description - disconnect to all channels
* @returns {void}
*/
private disconnectToAllChannels(): void {
this.channels.forEach((channel) => channel.disconnect());
}
/**
* @function publishEventToClient
* @description - publish event to client
* @param event - event name
* @param data - data to publish
* @returns {void}
*/
public publishEventToClient = (event: string, data?: unknown): void => {
this.logger.log('pubsub service @ publishEventToClient', { event, data });
if (!this.observers[event]) return;
this.observers[event].publish(data);
};
/**
* @function changeState
* @description change realtime component state and publish state to client
* @param state
* @returns {void}
*/
private changeState(state: RealtimeComponentState): void {
this.logger.log('realtime component @ changeState - state changed', state);
this.state = state;
this.publishEventToClient(RealtimeComponentEvent.REALTIME_STATE_CHANGED, this.state);
}
}