Skip to content
This repository was archived by the owner on Oct 18, 2024. It is now read-only.

Commit 5ac0bba

Browse files
committed
feat: return channel as a promise when connecting to it
1 parent ddd8a64 commit 5ac0bba

File tree

2 files changed

+17
-19
lines changed

2 files changed

+17
-19
lines changed

src/components/realtime/index.test.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -55,13 +55,13 @@ describe('realtime component', () => {
5555
});
5656

5757
describe('connect', () => {
58-
test('should log an error when trying to create a channel before start', () => {
58+
test('should return a promise when trying to create a channel before start', () => {
59+
RealtimeComponentInstance['start']();
5960
RealtimeComponentInstance['state'] = RealtimeComponentState.STOPPED;
6061

61-
const spy = jest.spyOn(RealtimeComponentInstance['logger'], 'log');
62-
RealtimeComponentInstance.connect('test');
62+
const channel = RealtimeComponentInstance.connect('test');
6363

64-
expect(spy).toHaveBeenCalled();
64+
expect(channel instanceof Promise).toBe(true);
6565
});
6666

6767
test('should create a new channel', () => {

src/components/realtime/index.ts

+13-15
Original file line numberDiff line numberDiff line change
@@ -41,25 +41,23 @@ export class Realtime extends BaseComponent {
4141
* @param name - channel name
4242
* @returns {Channel}
4343
*/
44-
public connect(name: string): Channel {
45-
if (this.state !== RealtimeComponentState.STARTED) {
46-
const message =
47-
"[SuperViz] Realtime component is not started yet. You can't connect to a channel before start";
48-
49-
this.logger.log(message);
50-
console.warn(message);
51-
return;
52-
}
53-
44+
public connect(name: string): Promise<Channel> {
5445
let channel: Channel = this.channels.get(name);
55-
56-
if (channel) return channel;
46+
if (channel) return channel as unknown as Promise<Channel>;
5747

5848
channel = new Channel(name, this.ioc, this.localParticipant, this.connectionLimit);
59-
6049
this.channels.set(name, channel);
6150

62-
return channel;
51+
if (this.state === RealtimeComponentState.STARTED) {
52+
return channel as unknown as Promise<Channel>;
53+
}
54+
55+
return new Promise((resolve) => {
56+
this.channel.subscribe(RealtimeComponentEvent.REALTIME_STATE_CHANGED, (state) => {
57+
if (state !== RealtimeComponentState.STARTED) return;
58+
resolve(channel);
59+
});
60+
});
6361
}
6462

6563
/**
@@ -75,7 +73,7 @@ export class Realtime extends BaseComponent {
7573
return;
7674
}
7775

78-
this.channel?.subscribe(event, callback);
76+
this.channel.subscribe(event, callback);
7977
};
8078

8179
/**

0 commit comments

Comments
 (0)