import { HttpErrorResponse } from '@angular/common/http'; import { catchError, map, switchMap, take } from 'rxjs/operators'; import { throwError, Observable } from 'rxjs'; import { MwHttpErrorHandler, MwHttpErrorHandlerOptions, } from './http-error-handler.service'; import { ErrorCodes, RequestOptions } from '../models'; import { HttpConfig } from '../types'; import { CustomHttpError } from '../models/custom-http-error.model'; import { AggHttpService } from './agg-http.service'; import { MwUrlService } from './url.service'; export class MwHttpBaseService { protected errorHandler: MwHttpErrorHandler; protected httpConfig?: HttpConfig; protected urlService: MwUrlService; constructor(public aggService: AggHttpService) { this.errorHandler = new MwHttpErrorHandler( this.aggService.translateService, this.aggService.notificationService ); this.urlService = this.aggService.urlService; this.aggService.httpConfigService .getConfig() .subscribe((t) => (this.httpConfig = t)); } addCustomerErrorHandler(errorHandlerPipe: any): void { this.errorHandler.addCustomErrorHandlerPipe(errorHandlerPipe); } rawRequest( method: string, url: string, options?: RequestOptions, errorHandlerOptions?: MwHttpErrorHandlerOptions ): Observable { const urlWithHost$ = this.urlService.replacePlaceholders(url); return ( this.throwErrorIfOffline(options) || urlWithHost$.pipe( switchMap((urlWithHost) => this.aggService.http .request(method, urlWithHost, options as any) .pipe( map((response) => this.handleResponse(response, options)), catchError((error: HttpErrorResponse) => throwError( this.errorHandler.handleError(error, errorHandlerOptions) ) ) ) ) ) ); } isOnline(): boolean { return navigator && navigator.onLine !== undefined && navigator.onLine; } protected getConfig(): HttpConfig | undefined { return this.httpConfig; } protected isOffline(): boolean { return ( navigator && navigator.onLine !== undefined && navigator.onLine === false ); } private handleResponse(response: any, options?: RequestOptions): T { let result: any = response; if (options?.responseType === 'blob') { result = new Blob([response], { type: options.mediaType }); } return result as T; } private throwErrorIfOffline(options?: {}): Observable | null { if (this.isOffline()) { return throwError( this.errorHandler.handleError( new CustomHttpError(ErrorCodes.Offline, 'No internet connection'), options ) ); } return null; } }