feat: add repeat requests in case of failure

This commit is contained in:
Polianin Nikita 2024-02-19 13:24:48 +03:00
parent 194e8b0070
commit 4463d54cfb
2 changed files with 27 additions and 2 deletions

View File

@ -1,4 +1,6 @@
export const environment = {
apiUrl: 'http://localhost:5269/api/v1/',
production: false
production: false,
maxRetry: 30,
retryDelay: 15000
}

View File

@ -1,9 +1,28 @@
import {Injectable} from '@angular/core';
import {catchError, Observable, throwError} from "rxjs";
import {catchError, mergeMap, Observable, retryWhen, throwError, timer} from "rxjs";
import {HttpClient} from "@angular/common/http";
import {NotifyColor, OpenNotifyService} from "@service/open-notify.service";
import {environment} from "@/config/environment";
export function retryWithInterval<T>(): (source: Observable<T>) => Observable<T> {
return (source: Observable<T>) =>
source.pipe(
retryWhen((errors: Observable<any>) =>
errors.pipe(
mergeMap((error, index) => {
if (index < (environment.maxRetry < 0 ? Infinity : environment.maxRetry - 1) && !error.status.toString().startsWith('4')) {
console.log(`Retrying after ${environment.retryDelay}ms...`);
return timer(environment.retryDelay);
} else {
console.error(`Exceeded maximum retries (${environment.maxRetry})`);
return throwError(error);
}
})
)
)
);
}
@Injectable({
providedIn: 'root'
})
@ -16,6 +35,7 @@ export class ApiService {
get<Type>(endpoint: string): Observable<Type> {
return this.http.get<Type>(this.urlApi + endpoint).pipe(
retryWithInterval<Type>(),
catchError(error => {
this.handleError(error);
return throwError(error);
@ -25,6 +45,7 @@ export class ApiService {
post<Type>(endpoint: string, data: any): Observable<Type> {
return this.http.post<Type>(this.urlApi + endpoint, data).pipe(
retryWithInterval<Type>(),
catchError(error => {
this.handleError(error);
return throwError(error);
@ -34,6 +55,7 @@ export class ApiService {
put<Type>(endpoint: string, data: any): Observable<Type> {
return this.http.put<Type>(this.urlApi + endpoint, data).pipe(
retryWithInterval<Type>(),
catchError(error => {
this.handleError(error);
return throwError(error);
@ -43,6 +65,7 @@ export class ApiService {
delete<Type>(endpoint: string): Observable<Type> {
return this.http.delete<Type>(this.urlApi + endpoint).pipe(
retryWithInterval<Type>(),
catchError(error => {
this.handleError(error);
return throwError(error);