@@ -2,6 +2,14 @@ import WebSocketClient from '@gamestdio/websocket';
22
33const randomIntUpTo = max => Math . floor ( Math . random ( ) * Math . floor ( max ) ) ;
44
5+ const knownEventTypes = [
6+ 'update' ,
7+ 'delete' ,
8+ 'notification' ,
9+ 'conversation' ,
10+ 'filters_changed' ,
11+ ] ;
12+
513export function connectStream ( path , pollingRefresh = null , callbacks = ( ) => ( { onConnect ( ) { } , onDisconnect ( ) { } , onReceive ( ) { } } ) ) {
614 return ( dispatch , getState ) => {
715 const streamingAPIBaseURL = getState ( ) . getIn ( [ 'meta' , 'streaming_api_base_url' ] ) ;
@@ -69,14 +77,42 @@ export function connectStream(path, pollingRefresh = null, callbacks = () => ({
6977
7078
7179export default function getStream ( streamingAPIBaseURL , accessToken , stream , { connected, received, disconnected, reconnected } ) {
72- const params = [ `stream=${ stream } ` ] ;
73-
74- const ws = new WebSocketClient ( `${ streamingAPIBaseURL } /api/v1/streaming/?${ params . join ( '&' ) } ` , accessToken ) ;
75-
76- ws . onopen = connected ;
77- ws . onmessage = e => received ( JSON . parse ( e . data ) ) ;
78- ws . onclose = disconnected ;
79- ws . onreconnect = reconnected ;
80+ const params = stream . split ( '&' ) ;
81+ stream = params . shift ( ) ;
82+
83+ if ( streamingAPIBaseURL . startsWith ( 'ws' ) ) {
84+ params . unshift ( `stream=${ stream } ` ) ;
85+ const ws = new WebSocketClient ( `${ streamingAPIBaseURL } /api/v1/streaming/?${ params . join ( '&' ) } ` , accessToken ) ;
86+
87+ ws . onopen = connected ;
88+ ws . onmessage = e => received ( JSON . parse ( e . data ) ) ;
89+ ws . onclose = disconnected ;
90+ ws . onreconnect = reconnected ;
91+
92+ return ws ;
93+ }
94+
95+ params . push ( `access_token=${ accessToken } ` ) ;
96+ const es = new EventSource ( `${ streamingAPIBaseURL } /api/v1/streaming/${ stream } ?${ params . join ( '&' ) } ` ) ;
97+
98+ let firstConnect = true ;
99+ es . onopen = ( ) => {
100+ if ( firstConnect ) {
101+ firstConnect = false ;
102+ connected ( ) ;
103+ } else {
104+ reconnected ( ) ;
105+ }
106+ } ;
107+ for ( let type of knownEventTypes ) {
108+ es . addEventListener ( type , ( e ) => {
109+ received ( {
110+ event : e . type ,
111+ payload : e . data ,
112+ } ) ;
113+ } ) ;
114+ }
115+ es . onerror = disconnected ;
80116
81- return ws ;
117+ return es ;
82118} ;
0 commit comments