Skip to content

Commit

Permalink
feat: add retryRequest function
Browse files Browse the repository at this point in the history
  • Loading branch information
Martin Kopeček committed Apr 29, 2024
1 parent ac1bc6d commit 18d46d2
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions frontend/src/app/services/api.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Injectable } from "@angular/core";
import axios, { AxiosError, AxiosResponse } from "axios";
import { BehaviorSubject } from "rxjs";
import { map } from "rxjs/operators";
import { BehaviorSubject, defer, fromEvent } from "rxjs";
import { filter, map, repeat, retry } from "rxjs/operators";
import { appConfig } from "src/config";
import { environment } from "src/environments/environment";
import { Logger } from "src/logger";
Expand All @@ -24,6 +24,23 @@ export type ApiError = AxiosError;

axios.defaults.withCredentials = true;

interface RetryRequestOptions {
maxRetries?: number;
onFocus?: boolean;
}

const tabFocusEvent = fromEvent(document, "visibilitychange").pipe(
filter(() => document.visibilityState === "visible"),
);

export function retryRequest<T, D>(request: () => Promise<AxiosResponse<T, D>>, options: RetryRequestOptions = {}) {
let o = defer(() => request());
if (options.maxRetries) o = o.pipe(retry(options.maxRetries));
if (options.onFocus) o = o.pipe(repeat({ delay: () => tabFocusEvent }));

return o;
}

@Injectable({
providedIn: "root",
})
Expand Down

0 comments on commit 18d46d2

Please sign in to comment.