@@ -15,12 +15,17 @@ export type TDerivApi = {
1515 authorize : ( requestData : AuthorizeRequest ) => Promise < AuthorizeResponse > ;
1616} ;
1717
18+ let attempts = 10 ;
19+ const RECONNECT_INTERVAL = attempts * 10000 ;
1820const PING_INTERVAL = 12000 ;
1921
2022export class ApiManager {
2123 private socket : WebSocket ;
2224 private derivApi : TDerivApi ;
2325 private pingInterval : NodeJS . Timer ;
26+ private reconnectInterval : NodeJS . Timer ;
27+ private is_websocket_connected : ( connection_value ) => boolean ;
28+ private is_websocket_authorized : ( connection_value ) => boolean ;
2429
2530 public static instance : ApiManager ;
2631 public static getInstance ( ) {
@@ -51,7 +56,9 @@ export class ApiManager {
5156 return this . derivApi . subscribe ( request ) as Observable < TSocketResponse < T > > ;
5257 }
5358
54- public authorize ( token : string ) {
59+ public authorize ( token : string , setIsConnected , setIsAuthorized ) {
60+ this . is_websocket_connected = setIsConnected ;
61+ this . is_websocket_authorized = setIsAuthorized ;
5562 return this . derivApi . authorize ( { authorize : token } ) ;
5663 }
5764 public logout ( ) {
@@ -62,14 +69,30 @@ export class ApiManager {
6269 if ( this . pingInterval ) {
6370 clearInterval ( this . pingInterval ) ;
6471 }
72+ if ( this . reconnectInterval ) {
73+ clearInterval ( this . reconnectInterval ) ;
74+ }
6575 this . socket . addEventListener ( 'open' , ( ) => {
76+ this . is_websocket_connected ?.( true ) ;
6677 this . pingInterval = setInterval ( ( ) => {
6778 this . socket . send ( JSON . stringify ( { ping : 1 } ) ) ;
6879 } , PING_INTERVAL ) ;
6980 } ) ;
7081
7182 this . socket . addEventListener ( 'close' , ( ) => {
83+ this . is_websocket_connected ?.( false ) ;
84+ this . is_websocket_authorized ?.( false ) ;
7285 clearInterval ( this . pingInterval ) ;
86+ this . socket = null ;
87+ if ( attempts > 0 ) {
88+ this . reconnectInterval = setTimeout ( this . init . bind ( this ) , RECONNECT_INTERVAL ) ;
89+ attempts -= 1 ;
90+ } else {
91+ window . alert (
92+ 'Sorry, the server is currently down. Please refresh the page or try again later' ,
93+ ) ;
94+ clearInterval ( this . reconnectInterval ) ;
95+ }
7396 } ) ;
7497
7598 this . socket . addEventListener ( 'error' , ( ) => {
0 commit comments