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

Commit

Permalink
Merge pull request #738 from SuperViz/feat/connect-channel-promise
Browse files Browse the repository at this point in the history
feat: connect channel promise
  • Loading branch information
carlossantos74 authored Aug 8, 2024
2 parents ddd8a64 + 5ac0bba commit 0439f87
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 19 deletions.
8 changes: 4 additions & 4 deletions src/components/realtime/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@ describe('realtime component', () => {
});

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

const spy = jest.spyOn(RealtimeComponentInstance['logger'], 'log');
RealtimeComponentInstance.connect('test');
const channel = RealtimeComponentInstance.connect('test');

expect(spy).toHaveBeenCalled();
expect(channel instanceof Promise).toBe(true);
});

test('should create a new channel', () => {
Expand Down
28 changes: 13 additions & 15 deletions src/components/realtime/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,25 +41,23 @@ export class Realtime extends BaseComponent {
* @param name - channel name
* @returns {Channel}
*/
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;
}

public connect(name: string): Promise<Channel> {
let channel: Channel = this.channels.get(name);

if (channel) return channel;
if (channel) return channel as unknown as Promise<Channel>;

channel = new Channel(name, this.ioc, this.localParticipant, this.connectionLimit);

this.channels.set(name, channel);

return channel;
if (this.state === RealtimeComponentState.STARTED) {
return channel as unknown as Promise<Channel>;
}

return new Promise((resolve) => {
this.channel.subscribe(RealtimeComponentEvent.REALTIME_STATE_CHANGED, (state) => {
if (state !== RealtimeComponentState.STARTED) return;
resolve(channel);
});
});
}

/**
Expand All @@ -75,7 +73,7 @@ export class Realtime extends BaseComponent {
return;
}

this.channel?.subscribe(event, callback);
this.channel.subscribe(event, callback);
};

/**
Expand Down

0 comments on commit 0439f87

Please sign in to comment.