Created
November 14, 2021 19:32
-
-
Save UserGalileo/5e8f369706403def32474b60817b4511 to your computer and use it in GitHub Desktop.
Retry Interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {HttpContextToken, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'; | |
import {Observable} from 'rxjs'; | |
import {retry, tap} from 'rxjs/operators'; | |
export const RETRY_COUNT = new HttpContextToken(() => 3); | |
export const ERROR_COUNT = new HttpContextToken(() => 0); | |
export class RetryInterceptor implements HttpInterceptor { | |
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
const retryCount = req.context.get(RETRY_COUNT); | |
return next.handle(req).pipe( | |
tap({ | |
error: () => { | |
req.context.set(ERROR_COUNT, req.context.get(ERROR_COUNT) + 1); | |
}, | |
}), | |
retry(retryCount) | |
); | |
} | |
} | |
/** | |
* Usage: | |
* | |
this.httpClient.get('...', { | |
context: new HttpContext().set(RETRY_COUNT, 5), | |
}).subscribe(() => {}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment