File tree Expand file tree Collapse file tree 2 files changed +18
-1
lines changed
Expand file tree Collapse file tree 2 files changed +18
-1
lines changed Original file line number Diff line number Diff line change @@ -39,6 +39,15 @@ export interface WebsocketOptions {
3939 * Callback allback which formats the websocket data stream.
4040 */
4141 formatMessage ?: ( ( message : any ) => string ) | undefined ;
42+ /**
43+ * Set to true, to reconnect the WebSocket automatically.
44+ */
45+ reconnect ?: boolean ;
46+ /**
47+ * Set the time to wait between reconnects in seconds.
48+ * Default is 1s
49+ */
50+ reconnectWait ?: number
4251}
4352
4453export interface ErrorStatus extends Error {
Original file line number Diff line number Diff line change @@ -10,6 +10,7 @@ export default (url: string | URL, options: WebsocketOptions) => {
1010 const emitter = mitt ( ) ;
1111 let encodedLog = new Uint8Array ( ) ;
1212 let overage : any = null ;
13+ let aborted : boolean = false ;
1314
1415 emitter . on ( "data" , ( data ) => {
1516 encodedLog = bufferConcat (
@@ -46,6 +47,10 @@ export default (url: string | URL, options: WebsocketOptions) => {
4647 } ) ;
4748 socket . addEventListener ( "close" , ( e ) => {
4849 onClose && onClose ( e ) ;
50+ if ( ! aborted && options . reconnect ) {
51+ const timeout = options . reconnectWait ?? 1 ;
52+ setTimeout ( ( ) => emitter . emit ( "start" ) , timeout * 1000 ) ;
53+ }
4954 } ) ;
5055
5156 socket . addEventListener ( "error" , ( err ) => {
@@ -65,7 +70,10 @@ export default (url: string | URL, options: WebsocketOptions) => {
6570 emitter . emit ( "data" , msg ) ;
6671 } ) ;
6772
68- emitter . on ( "abort" , ( ) => socket . close ( ) ) ;
73+ emitter . on ( "abort" , ( ) => {
74+ aborted = true ;
75+ socket . close ( )
76+ } ) ;
6977 } catch ( err ) {
7078 emitter . emit ( "error" , err ) ;
7179 }
You can’t perform that action at this time.
0 commit comments