All files / lib/services/http-handlers http-handlers.service.ts

96.82% Statements 61/63
86.95% Branches 20/23
95.83% Functions 23/24
98.36% Lines 60/61

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233                                                  1x 21x   21x   21x   21x   21x   21x               1x                       1x 3x 3x                         2x 2x     1x   2x                             2x 2x     1x 1x   2x                       1x                     3x   3x 1x 2x 2x 2x 2x     2x   2x   2x 1x 1x 1x   1x 1x       3x   3x                   1x 1x 1x 1x 1x               2x 1x                 4x 1x 1x 1x                   7x 7x 7x                 3x 3x 3x                 2x 2x               4x 2x   2x          
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { ApolloLink, CombinedGraphQLErrors, ObservableQuery, ServerError, ServerParseError } from '@apollo/client/core';
import { ErrorLink } from '@apollo/client/link/error';
import { HTTP_STATUS, WEB_CLIENT_APP_ENV } from '@app/client-util';
import { Store } from '@ngrx/store';
import { Apollo } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import memo from 'memo-decorator';
import { MonoTypeOperatorFunction, Observable, of } from 'rxjs';
import { catchError, finalize, map, tap, timeout } from 'rxjs/operators';
 
import { httpProgressAction } from '../../http-progress.actions';
import { IHttpProgressState } from '../../http-progress.interface';
import { AppToasterService } from '../toaster/toaster.service';
 
export type TGqlClient = 'graphql';
 
/**
 * Handlers to work with http requests.
 */
@Injectable({
  providedIn: 'root',
})
export class AppHttpHandlersService {
  private readonly store = inject(Store<IHttpProgressState>);
 
  private readonly toaster = inject(AppToasterService);
 
  private readonly httpLink = inject(HttpLink);
 
  private readonly router = inject(Router);
 
  private readonly env = inject(WEB_CLIENT_APP_ENV);
 
  public readonly defaultHttpTimeout = 10000;
 
  /**
   * Gets gql http headers.
   * @param userToken user token
   * @returns the gql headers observable
   */
  public getGraphQLHttpHeaders(userToken: string) {
    return new HttpHeaders({
      Authorization: `Token ${userToken}`,
    });
  }
 
  /**
   * Returns API base url concatenated with provided endpoint path.
   * Adds preceding slash before endpoint path if it is missing.
   * @param path endpoint path
   * @returns an endpoint url
   */
  @memo()
  public getEndpoint(path: string): string {
    const endpoint = /^\/.*$/.test(path) ? path : `/${path}`;
    return `${this.env.api}${endpoint}`;
  }
 
  /**
   * Pipes an http response.
   * Attaches settings:
   * - timeout
   * - error handler
   * - progress indicator
   * @param observable input observable
   * @returns a piped observable
   */
  public pipeHttpResponse<T>(observable: Observable<T>) {
    this.store.dispatch(httpProgressAction.start({ payload: { mainView: true } }));
    return observable.pipe(
      timeout(this.defaultHttpTimeout),
      this.tapError<T>(),
      catchError(err => this.handleError(err)),
      finalize(() => {
        this.store.dispatch(httpProgressAction.stop({ payload: { mainView: true } }));
      }),
    );
  }
 
  /**
   * Pipes a gql response.
   * Attaches settings:
   * - timeout
   * - error handler
   * - progress indicator
   * @param observable input observable
   * @returns a piped observable
   */
  public pipeGqlResponse<T>(observable: Observable<ObservableQuery.Result<T> | ApolloLink.Result<T> | Apollo.MutateResult<T>>) {
    this.store.dispatch(httpProgressAction.start({ payload: { mainView: true } }));
    return observable.pipe(
      timeout(this.defaultHttpTimeout),
      this.tapError(),
      map(result => ('data' in result ? result.data : result)),
      catchError(err => this.handleGqlError(err)),
      finalize(() => {
        this.store.dispatch(httpProgressAction.stop({ payload: { mainView: true } }));
      }),
    );
  }
 
  /**
   * Gets the gql network link.
   * @param uri universal resource indentifier
   * @param userToken user token
   * @returns gql link
   */
  private createGqlNetworkLink(uri: HttpLink.Options['uri'], userToken: string) {
    return this.httpLink.create({
      uri,
      headers: new HttpHeaders().append('Authorization', `Token ${userToken}`),
    });
  }
 
  /**
   * Gets the gql error link handler.
   * @returns apollo error link handler
   */
  public gqlErrorLinkHandler(error: ErrorLink.ErrorHandlerOptions['error']) {
    let errorMessage = '';
 
    if (CombinedGraphQLErrors.is(error)) {
      error.errors.map(({ message, extensions }) => {
        console.error('Apollo linkHandler [GraphQL error]: ', message);
        const code = extensions?.['code'] as string;
        const result = `[GraphQL error ${code}]: ${message}`;
        errorMessage += result;
      });
    } else {
      console.error('Apollo linkHandler [Network error]: ', error);
 
      Iif (error instanceof HttpErrorResponse) {
        errorMessage += (error.error as { detail: string }).detail;
      } else if (ServerParseError.is(error) || ServerError.is(error)) {
        const code = error.statusCode;
        const result = `[Network error ${code}]: ${error?.message}`;
        errorMessage += result;
      } else {
        const result = `[Unknown error]: ${error?.message}`;
        errorMessage += result;
      }
    }
 
    errorMessage = errorMessage.length === 0 ? 'Graphql request error' : errorMessage;
 
    this.toaster.showToaster(errorMessage, 'error');
  }
 
  /**
   * Creates the gql link with an error handler.
   * @param userToken user token
   * @param name the client name
   * @returns apollo link observable
   */
  public createGqlLink(userToken: string, name: TGqlClient = 'graphql'): ApolloLink {
    const uri = this.getEndpoint(name);
    const uriFn = this.gqlUriFunction(uri);
    const linkHandler: ApolloLink = new ErrorLink((options: ErrorLink.ErrorHandlerOptions) => this.gqlErrorLinkHandler(options.error));
    const networkLink = this.createGqlNetworkLink(uriFn, userToken);
    return linkHandler.concat(networkLink);
  }
 
  /**
   * Gql URI function.
   * @param uri graphql endpoint
   */
  public gqlUriFunction(uri: string) {
    return ((operation: ApolloLink.Operation) => {
      return `${uri}?operation=${operation.operationName}`;
    }) as unknown as HttpLink.Options['uri'];
  }
 
  /**
   * Check error status, and reset token if status is 401.
   * @param status error status
   */
  public checkErrorStatusAndRedirect(status: HTTP_STATUS): void {
    if (status === HTTP_STATUS.UNAUTHORIZED) {
      const message = 'Something went wrong during authorization or you are not authorized to see this content.';
      this.toaster.showToaster(message, 'error');
      void this.router.navigate([{ outlets: { primary: [''] } }]);
    }
  }
 
  /**
   * Gets an error message from an http error response.
   * @param error http error response
   * @returns an error message
   */
  public getErrorMessage(error: HttpErrorResponse): string {
    const message: string | undefined = error.message ? error.message : error.error;
    const result: string = typeof message !== 'undefined' ? message : error.status ? `${error.status} - ${error.name}` : 'Server error';
    return result;
  }
 
  /**
   * Handles error.
   * @param error error object
   * @returns an empty observable
   */
  public handleError(error: HttpErrorResponse): Observable<never> {
    const message = this.getErrorMessage(error);
    this.toaster.showToaster(message, 'error');
    return of();
  }
 
  /**
   * Handles a graphQL error.
   * @param error error message
   * @returns an empty observable
   */
  public handleGqlError(error: string): Observable<never> {
    this.toaster.showToaster(error, 'error');
    return of();
  }
 
  /**
   * Taps errors.
   * @returns a monotype operator function
   */
  public tapError<T>(): MonoTypeOperatorFunction<T> {
    return tap({
      next: (): void => void 0,
      error: (error: HttpErrorResponse) => {
        this.checkErrorStatusAndRedirect(error.status);
      },
    });
  }
}