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 #598 from SuperViz/feat/io
Browse files Browse the repository at this point in the history
feat: event subscribers and events payload
  • Loading branch information
carlossantos74 authored Mar 13, 2024
2 parents f8a9dd2 + efa0d5a commit 5aefc59
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/components/realtime/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as Socket from '@superviz/socket-client';

import { ComponentLifeCycleEvent } from '../../common/types/events.types';
import { StoreType } from '../../common/types/stores.types';
import { Logger } from '../../common/utils';
import { Logger, Observer } from '../../common/utils';
import { RealtimeMessage } from '../../services/realtime/ably/types';
import { BaseComponent } from '../base';
import { ComponentNames } from '../types';
Expand Down Expand Up @@ -38,10 +39,6 @@ export class Realtime extends BaseComponent {
protected start(): void {
this.logger.log('started');

this.callbacksToSubscribeWhenJoined.forEach(({ event, callback }) => {
this.room.on(event, callback);
});

this.subscribeToRealtimeEvents();
}

Expand All @@ -53,6 +50,11 @@ export class Realtime extends BaseComponent {
* @returns {void}
*/
public publish = (event: string, data?: unknown): void => {
if (Object.values(ComponentLifeCycleEvent).includes(event as ComponentLifeCycleEvent)) {
this.publishEventToClient(event, data);
return;
}

if (this.state !== RealtimeComponentState.STARTED) {
const message = `Realtime component is not started yet. You can't publish event ${event} before start`;
this.logger.log(message);
Expand All @@ -76,6 +78,10 @@ export class Realtime extends BaseComponent {
return;
}

if (!this.observers[event]) {
this.observers[event] = new Observer();
}

this.observers[event].subscribe(callback);
};

Expand Down Expand Up @@ -163,11 +169,20 @@ export class Realtime extends BaseComponent {

this.logger.log('joined room');
this.changeState(RealtimeComponentState.STARTED);

this.callbacksToSubscribeWhenJoined.forEach(({ event, callback }) => {
this.subscribe(event, callback);
});
});

this.room.on<RealtimeData>('message', (event) => {
this.logger.log('message received', event);
this.publishEventToClient(event.data.name, event.data.payload);
this.publishEventToClient(event.data.name, {
data: event.data.payload,
participantId: event.presence.id,
name: event.data.name,
timestamp: event.timestamp,
} as RealtimeMessage);
});
}

Expand Down

0 comments on commit 5aefc59

Please sign in to comment.