@@ -17,8 +17,9 @@ const defaultOptions: EventSourceOptions = {
1717 method : 'GET' ,
1818 pollingInterval : 5000 ,
1919 timeout : 0 ,
20- timeoutBeforeConnection : 500 ,
20+ timeoutBeforeConnection : 0 ,
2121 withCredentials : false ,
22+ retryAndHandleError : undefined ,
2223} ;
2324
2425export default class EventSource < E extends string = never > {
@@ -49,6 +50,7 @@ export default class EventSource<E extends string = never> {
4950 private xhr : XMLHttpRequest = new XMLHttpRequest ( ) ;
5051 private pollTimer : any ;
5152 private pollingInterval : number ;
53+ private retryAndHandleError ?: ( err : any ) => boolean ;
5254
5355 constructor ( url : string , options ?: EventSourceOptions ) {
5456 const opts = {
@@ -65,6 +67,7 @@ export default class EventSource<E extends string = never> {
6567 this . body = opts . body ;
6668 this . debug = opts . debug ! ;
6769 this . pollingInterval = opts . pollingInterval ! ;
70+ this . retryAndHandleError = opts . retryAndHandleError ;
6871
6972 this . pollAgain ( this . timeoutBeforeConnection , true ) ;
7073 }
@@ -147,7 +150,21 @@ export default class EventSource<E extends string = never> {
147150
148151 if ( this . xhr . readyState === XMLHttpRequest . DONE ) {
149152 this . logDebug ( '[EventSource][onreadystatechange][ERROR] Response status error.' ) ;
150- this . pollAgain ( this . pollingInterval , false ) ;
153+
154+ if ( ! this . retryAndHandleError ) {
155+ // default implementation
156+ this . pollAgain ( this . pollingInterval , false ) ;
157+ } else {
158+ // custom retry logic
159+ const shouldRetry = this . retryAndHandleError ( {
160+ status : this . xhr . status ,
161+ message : this . xhr . responseText ,
162+ } ) ;
163+
164+ if ( shouldRetry ) {
165+ this . pollAgain ( this . pollingInterval , true ) ;
166+ }
167+ }
151168 }
152169 }
153170 } ;
@@ -290,7 +307,7 @@ export default class EventSource<E extends string = never> {
290307 this . onerror ( data ) ;
291308 break ;
292309 case 'retry' :
293- this . onretrying ( ) ;
310+ this . onretrying ( { delayMillis : this . pollingInterval } ) ;
294311 break ;
295312 default :
296313 break ;
@@ -310,5 +327,5 @@ export default class EventSource<E extends string = never> {
310327 onopen ( ) { }
311328 onclose ( ) { }
312329 onerror ( _err : any ) { }
313- onretrying ( ) { }
330+ onretrying ( _e : any ) { }
314331}
0 commit comments