All files / src/app retry.interceptor.ts

13.33% Statements 2/15
0% Branches 0/7
0% Functions 0/6
14.28% Lines 2/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                  1x                       1x                                                              
import {
  HttpEvent, HttpHandler, HttpInterceptor, HttpRequest
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable, throwError, timer } from 'rxjs';
import { mergeMap, retryWhen } from 'rxjs/operators';
import { HttpRetryPolicy, HttpRetryPolicyNames } from './app.interfaces';
 
const retryPolicies: { [name in HttpRetryPolicyNames]: HttpRetryPolicy } = {
  test: {
    excludedStatusCodes: [401, 403],
    retryPattern: [50, 500, 1000, 2000]
  },
  none: {
    excludedStatusCodes: [],
    retryPattern: []
  }
};
 
@Injectable()
export class RetryInterceptor implements HttpInterceptor {
  constructor(
    private route: ActivatedRoute
  ) {}
 
  // eslint-disable-next-line class-methods-use-this
  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const routeData = this.route.firstChild?.routeConfig?.data ?? { httpRetryPolicy: 'none' };
    const retryPolicyName = routeData.httpRetryPolicy;
    const retryPolicy = retryPolicies[retryPolicyName as HttpRetryPolicyNames] ?? retryPolicies.none;
    return next.handle(request)
      .pipe(
        retryWhen(
          (attempts: Observable<any>) => attempts.pipe(
            mergeMap((error, i) => {
              const retryAttempt = i + 1;
              Iif (
                retryAttempt > retryPolicy.retryPattern.length ||
                retryPolicy.excludedStatusCodes.find(e => e === error.status)
              ) {
                return throwError(() => { throw error; });
              }
              // eslint-disable-next-line no-console
              console.log(`Attempt ${retryAttempt}: retrying in ${retryPolicy.retryPattern[i]}ms`);
              return timer(retryPolicy.retryPattern[i]);
            })
          )
        )
      );
  }
}