Skip to content

Instantly share code, notes, and snippets.

@junibrosas
Created February 5, 2019 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junibrosas/a82aedcce247f8f9d1bbfe9a655467d0 to your computer and use it in GitHub Desktop.
Save junibrosas/a82aedcce247f8f9d1bbfe9a655467d0 to your computer and use it in GitHub Desktop.
These are snippet compilation about scenarios using RxJS
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