You should split the responsibles of this interceptor to multiple interceptor, something like below:
Inteceptors token in AppModule:
// Important: Order of Interceptors matters!
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: RetryInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: AuthTokensManagementInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: TelemetryInterceptor, multi: true },
];
Auth token interceptor:
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return of(req).pipe(
mergeMap(() => getAcessToken() /*and add it to local storage*/)
mergeMap((accessToken: string) => {
if (accessToken) {
req = req.clone({
headers: req.headers.set(AuthorizationHeader, `${accessToken}`)
})
}
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401)
this.authTokensManager.invalidateAccessToken(error.url);
}
}
return throwError(error);
})
);
}));
}
Retry Interceptor:
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return of(req).pipe(
mergeMap((req: HttpRequest<any>) => {
return next.handle(req).pipe(
// Will continue the pipe if a request attempt has succeeded without errors, or exceeded max retries.
retryWhen((errors: Observable<any>) => errors.pipe(
// Enable only 2 retries, +1 for the original request.
take(this.maxRetries + 1),
skipWhile(() => disableRetry),
mergeMap((err: HttpErrorResponse, i: number) => {
if (i >= this.maxRetries) {
return throwError(err);
}
const errorCode = err.status;
if (errorCode == 401) {
return of(err);
}
return throwError(err);
}),
))
)
})
);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…