@@ -4,9 +4,11 @@ import { useCentrifuge, useEventsRequests } from "../io";
44import { useConnectionStore } from "~/stores/connections" ;
55import { useEventStore } from "~/stores/events" ;
66
7- const CHECK_CONNECTION_INTERVAL = 10000
7+ const CHECK_CONNECTION_INTERVAL : number = 10000
8+ let isEventsEmitted : boolean = false
9+
810export const useApiTransport = ( ) => {
9- const { centrifuge } = useCentrifuge ( )
11+ const { centrifuge} = useCentrifuge ( )
1012 const eventsStore = useEventStore ( )
1113 const connectionStore = useConnectionStore ( )
1214 const {
@@ -21,37 +23,44 @@ export const useApiTransport = () => {
2123
2224 const getWSConnection = ( ) => connectionStore . isConnectedWS
2325 const checkWSConnectionFail = ( onConnectionLost : ( ) => void ) => {
24- if ( ! getWSConnection ( ) ) {
26+ if ( ! getWSConnection ( ) ) {
2527 onConnectionLost ( )
2628 }
2729 setTimeout ( ( ) => {
2830 checkWSConnectionFail ( onConnectionLost )
2931 } , CHECK_CONNECTION_INTERVAL )
3032 }
3133
32- centrifuge . on ( 'connected' , ( ) => {
33- connectionStore . addWSConnection ( )
34- } ) ;
34+ const subscribeToEvents = ( ) : void => {
35+ centrifuge . on ( 'connected' , ( ) => {
36+ connectionStore . addWSConnection ( )
37+ } ) ;
3538
36- centrifuge . on ( 'disconnected' , ( ) => {
37- connectionStore . removeWSConnection ( )
38- } ) ;
39+ centrifuge . on ( 'disconnected' , ( ) => {
40+ connectionStore . removeWSConnection ( )
41+ } ) ;
3942
40- centrifuge . on ( 'error' , ( ) => {
41- connectionStore . removeWSConnection ( )
42- } )
43+ centrifuge . on ( 'error' , ( ) => {
44+ connectionStore . removeWSConnection ( )
45+ } )
4346
44- centrifuge . on ( 'message' , ( ) => {
45- connectionStore . addWSConnection ( )
46- } )
47+ centrifuge . on ( 'message' , ( ) => {
48+ connectionStore . addWSConnection ( )
49+ } )
4750
48- centrifuge . on ( 'publication' , ( ctx ) => {
49- // We need to handle only events from the channel 'events' with event name 'event.received'
50- if ( ctx . channel === 'events' && ctx . data ?. event === 'event.received' ) {
51- const event = ctx ?. data ?. data || null
52- eventsStore . addList ( [ event ] ) ;
53- }
54- } ) ;
51+ centrifuge . on ( 'publication' , ( ctx ) => {
52+ // We need to handle only events from the channel 'events' with event name 'event.received'
53+ if ( ctx . channel === 'events' && ctx . data ?. event === 'event.received' ) {
54+ const event = ctx ?. data ?. data || null
55+ eventsStore . addList ( [ event ] ) ;
56+ }
57+ } ) ;
58+ }
59+
60+ if ( ! isEventsEmitted ) {
61+ subscribeToEvents ( )
62+ isEventsEmitted = true
63+ }
5564
5665 checkWSConnectionFail ( async ( ) => {
5766 const events = await getAll ( ) ;
@@ -85,7 +94,7 @@ export const useApiTransport = () => {
8594 }
8695
8796 if ( getWSConnection ( ) ) {
88- return centrifuge . rpc ( `delete:api/events` , { uuids } )
97+ return centrifuge . rpc ( `delete:api/events` , { uuids} )
8998 }
9099
91100 return deleteList ( uuids ) ;
0 commit comments