Created
February 5, 2019 05:57
-
-
Save junibrosas/a82aedcce247f8f9d1bbfe9a655467d0 to your computer and use it in GitHub Desktop.
These are snippet compilation about scenarios using RxJS
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 { throwError as observableThrowError, from as observableFrom, Observable, TimeoutError, of } from 'rxjs'; | |
import { mergeMap, catchError, timeout, retryWhen, concatMap } from 'rxjs/operators'; | |
import { Injectable } from '@angular/core'; | |
import { HttpClient, HttpParams } from '@angular/common/http'; | |
import { EntityService } from '../entity/entity.service'; | |
import { UserService } from '../../promoter/legacy/_common/services/user-service/user.service'; | |
import rmaProperties from '../../../rmaProperties'; | |
@Injectable() | |
export class RmaHttpClient { | |
isAgency: boolean; | |
timeoutValue = 5000; // milliseconds | |
retryValue = 3; | |
constructor( | |
private http: HttpClient, | |
private userService: UserService, | |
private entityService: EntityService, | |
) { | |
this.entityService.isAgency().subscribe((isAgency) => { | |
this.isAgency = isAgency; | |
}); | |
} | |
private prefixUrl(url: string): string { | |
return `${rmaProperties.apiUrl}${url}`; | |
} | |
/** | |
Here we you `retryWhen` to retry an observable sequence using en error based on custom criteria. | |
We also use `timeout` to throw error if no value emitted before specified duration. | |
*/ | |
get<R>(url: string, httpParams?: HttpParams): Observable<R> { | |
url = this.prefixUrl(url); | |
return this.http.get<R>(url, { params: httpParams, withCredentials: true }) | |
.pipe( | |
timeout(this.timeoutValue), | |
retryWhen(errors => this.retryOnTimeout(errors, this.retryValue)), | |
catchError((e) => observableThrowError(e.error || e)) | |
); | |
} | |
post<R>(url: string, data: any): Observable<R> { | |
url = this.prefixUrl(url); | |
return this.http.post<R>(url, data, { withCredentials: true }) | |
.pipe(catchError((e) => observableThrowError(e.error || e))); | |
} | |
delete<R>(url: string): Observable<R> { | |
url = this.prefixUrl(url); | |
return this.http.delete<R>(url, { withCredentials: true }) | |
.pipe(catchError((e) => observableThrowError(e.error || e))); | |
} | |
retryOnTimeout(errors: Observable<any>, numberOfRetries = 3): Observable<any> { | |
return errors.pipe( | |
concatMap((error, index) => { | |
if (index === numberOfRetries) { | |
console.error(`Max number of retries reached for http call!`); | |
throw(error); | |
} | |
if (error instanceof TimeoutError) { | |
console.error(`Timeout(${index}) reached for http call, retry..`); | |
return of(error); | |
} | |
throw(error); | |
}) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment