diff --git a/src/config/environment.ts b/src/config/environment.ts index be42646..cde2103 100644 --- a/src/config/environment.ts +++ b/src/config/environment.ts @@ -1,4 +1,6 @@ export const environment = { apiUrl: 'http://localhost:5269/api/v1/', - production: false + production: false, + maxRetry: 30, + retryDelay: 15000 } diff --git a/src/services/api.service.ts b/src/services/api.service.ts index eaea148..7970a27 100644 --- a/src/services/api.service.ts +++ b/src/services/api.service.ts @@ -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(): (source: Observable) => Observable { + return (source: Observable) => + source.pipe( + retryWhen((errors: Observable) => + 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(endpoint: string): Observable { return this.http.get(this.urlApi + endpoint).pipe( + retryWithInterval(), catchError(error => { this.handleError(error); return throwError(error); @@ -25,6 +45,7 @@ export class ApiService { post(endpoint: string, data: any): Observable { return this.http.post(this.urlApi + endpoint, data).pipe( + retryWithInterval(), catchError(error => { this.handleError(error); return throwError(error); @@ -34,6 +55,7 @@ export class ApiService { put(endpoint: string, data: any): Observable { return this.http.put(this.urlApi + endpoint, data).pipe( + retryWithInterval(), catchError(error => { this.handleError(error); return throwError(error); @@ -43,6 +65,7 @@ export class ApiService { delete(endpoint: string): Observable { return this.http.delete(this.urlApi + endpoint).pipe( + retryWithInterval(), catchError(error => { this.handleError(error); return throwError(error);